From f4eb96933adff53997edbea9a444b2d213c62a4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Courtine?= Date: Fri, 26 Oct 2018 11:24:14 +0200 Subject: [PATCH] [Rust] Client library choice between hyper and reqwest (#1258) * Port of PR https://github.com/swagger-api/swagger-codegen/pull/8804. * Correction of conflict with PR #528 (missing template file). * Add rust-reqwest samples to Circle CI tests. * Add integration test pom.xml file with launcher to trigger cargo execution. * Deduplicate Maven project name. * Fix "api_key" header for Petstore. * Better API key management. * Fix query param for lists of objects other than strings (numbers, etc.). * Update to reqwest 0.9, and refactor of header management (using reqwest transition feature). * Merge scripts generating rust-hyper and rust-reqwest samples. * Consistent full stops. * Use raw variables in all Rust mustache templates. * Replace production build in CI with a quick simple check. * Update samples. * Finish Reqwest 0.9 migration (removing "hyper 0.11" transition feature). * Configuration implements Default trait. * API template reorganized: HashMap is not required anymore. * Revert "Merge scripts generating rust-hyper and rust-reqwest samples." This reverts commit 970f996566a740045f2a986fd70fc70f11952925. * Remove deprecated "-XX:MaxPermSize" java arg. --- bin/rust-petstore.sh | 4 +- bin/rust-reqwest-petstore.sh | 32 ++ .../codegen/languages/RustClientCodegen.java | 86 +++-- .../src/main/resources/rust/Cargo.mustache | 21 +- .../src/main/resources/rust/README.mustache | 20 +- .../src/main/resources/rust/api_doc.mustache | 16 +- .../resources/rust/{ => hyper}/api.mustache | 22 +- .../rust/{ => hyper}/api_mod.mustache | 4 +- .../rust/{ => hyper}/client.mustache | 8 +- .../rust/{ => hyper}/configuration.mustache | 2 +- .../src/main/resources/rust/lib.mustache | 16 + .../src/main/resources/rust/model.mustache | 32 +- .../main/resources/rust/model_doc.mustache | 4 +- .../main/resources/rust/reqwest/api.mustache | 113 +++++++ .../resources/rust/reqwest/api_mod.mustache | 38 +++ .../resources/rust/reqwest/client.mustache | 55 ++++ .../rust/reqwest/configuration.mustache | 39 +++ pom.xml | 1 + .../client/petstore/rust-reqwest/.gitignore | 3 + .../rust-reqwest/.openapi-generator-ignore | 23 ++ .../rust-reqwest/.openapi-generator/VERSION | 1 + .../client/petstore/rust-reqwest/.travis.yml | 1 + .../client/petstore/rust-reqwest/Cargo.toml | 13 + .../client/petstore/rust-reqwest/README.md | 97 ++++++ .../petstore/rust-reqwest/docs/ApiResponse.md | 12 + .../petstore/rust-reqwest/docs/Category.md | 11 + .../petstore/rust-reqwest/docs/Order.md | 15 + .../client/petstore/rust-reqwest/docs/Pet.md | 15 + .../petstore/rust-reqwest/docs/PetApi.md | 259 +++++++++++++++ .../petstore/rust-reqwest/docs/StoreApi.md | 115 +++++++ .../client/petstore/rust-reqwest/docs/Tag.md | 11 + .../client/petstore/rust-reqwest/docs/User.md | 17 + .../petstore/rust-reqwest/docs/UserApi.md | 221 +++++++++++++ .../client/petstore/rust-reqwest/git_push.sh | 52 +++ samples/client/petstore/rust-reqwest/pom.xml | 46 +++ .../petstore/rust-reqwest/src/apis/client.rs | 37 +++ .../rust-reqwest/src/apis/configuration.rs | 48 +++ .../petstore/rust-reqwest/src/apis/mod.rs | 32 ++ .../petstore/rust-reqwest/src/apis/pet_api.rs | 298 ++++++++++++++++++ .../rust-reqwest/src/apis/store_api.rs | 155 +++++++++ .../rust-reqwest/src/apis/user_api.rs | 263 ++++++++++++++++ .../client/petstore/rust-reqwest/src}/lib.rs | 3 +- .../rust-reqwest/src/models/api_response.rs | 90 ++++++ .../rust-reqwest/src/models/category.rs | 70 ++++ .../petstore/rust-reqwest/src/models/mod.rs | 15 + .../petstore/rust-reqwest/src/models/order.rs | 151 +++++++++ .../petstore/rust-reqwest/src/models/pet.rs | 145 +++++++++ .../petstore/rust-reqwest/src/models/tag.rs | 70 ++++ .../petstore/rust-reqwest/src/models/user.rs | 191 +++++++++++ .../petstore/rust/.openapi-generator/VERSION | 2 +- samples/client/petstore/rust/Cargo.toml | 14 +- samples/client/petstore/rust/docs/PetApi.md | 4 +- samples/client/petstore/rust/docs/UserApi.md | 4 +- samples/client/petstore/rust/pom.xml | 3 +- samples/client/petstore/rust/src/lib.rs | 4 +- 55 files changed, 2912 insertions(+), 112 deletions(-) create mode 100755 bin/rust-reqwest-petstore.sh rename modules/openapi-generator/src/main/resources/rust/{ => hyper}/api.mustache (53%) rename modules/openapi-generator/src/main/resources/rust/{ => hyper}/api_mod.mustache (92%) rename modules/openapi-generator/src/main/resources/rust/{ => hyper}/client.mustache (76%) rename modules/openapi-generator/src/main/resources/rust/{ => hyper}/configuration.mustache (88%) create mode 100644 modules/openapi-generator/src/main/resources/rust/lib.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust/reqwest/client.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache create mode 100644 samples/client/petstore/rust-reqwest/.gitignore create mode 100644 samples/client/petstore/rust-reqwest/.openapi-generator-ignore create mode 100644 samples/client/petstore/rust-reqwest/.openapi-generator/VERSION create mode 100644 samples/client/petstore/rust-reqwest/.travis.yml create mode 100644 samples/client/petstore/rust-reqwest/Cargo.toml create mode 100644 samples/client/petstore/rust-reqwest/README.md create mode 100644 samples/client/petstore/rust-reqwest/docs/ApiResponse.md create mode 100644 samples/client/petstore/rust-reqwest/docs/Category.md create mode 100644 samples/client/petstore/rust-reqwest/docs/Order.md create mode 100644 samples/client/petstore/rust-reqwest/docs/Pet.md create mode 100644 samples/client/petstore/rust-reqwest/docs/PetApi.md create mode 100644 samples/client/petstore/rust-reqwest/docs/StoreApi.md create mode 100644 samples/client/petstore/rust-reqwest/docs/Tag.md create mode 100644 samples/client/petstore/rust-reqwest/docs/User.md create mode 100644 samples/client/petstore/rust-reqwest/docs/UserApi.md create mode 100644 samples/client/petstore/rust-reqwest/git_push.sh create mode 100644 samples/client/petstore/rust-reqwest/pom.xml create mode 100644 samples/client/petstore/rust-reqwest/src/apis/client.rs create mode 100644 samples/client/petstore/rust-reqwest/src/apis/configuration.rs create mode 100644 samples/client/petstore/rust-reqwest/src/apis/mod.rs create mode 100644 samples/client/petstore/rust-reqwest/src/apis/pet_api.rs create mode 100644 samples/client/petstore/rust-reqwest/src/apis/store_api.rs create mode 100644 samples/client/petstore/rust-reqwest/src/apis/user_api.rs rename {modules/openapi-generator/src/main/resources/rust => samples/client/petstore/rust-reqwest/src}/lib.rs (76%) create mode 100644 samples/client/petstore/rust-reqwest/src/models/api_response.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/category.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/mod.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/order.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/pet.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/tag.rs create mode 100644 samples/client/petstore/rust-reqwest/src/models/user.rs diff --git a/bin/rust-petstore.sh b/bin/rust-petstore.sh index ffab5a47afb..b58d3de7dd6 100755 --- a/bin/rust-petstore.sh +++ b/bin/rust-petstore.sh @@ -26,7 +26,7 @@ then fi # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="generate -t modules/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust -DpackageName=petstore_client $@" +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust -DpackageName=petstore_client --library=hyper $@" java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/rust-reqwest-petstore.sh b/bin/rust-reqwest-petstore.sh new file mode 100755 index 00000000000..054a757c5fa --- /dev/null +++ b/bin/rust-reqwest-petstore.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar" + +if [ ! -f "$executable" ] +then + mvn -B clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust-reqwest -DpackageName=petstore_client --library=reqwest $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index da9763a281f..c7cc86038cf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -17,27 +17,17 @@ package org.openapitools.codegen.languages; +import com.google.common.base.Strings; 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.CliOption; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenType; -import org.openapitools.codegen.DefaultCodegen; -import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.*; import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { @@ -45,6 +35,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; + public static final String HYPER_LIBRARY = "hyper"; + public static final String REQWEST_LIBRARY = "reqwest"; + protected String packageName = "openapi"; protected String packageVersion = "1.0.0"; protected String apiDocPath = "docs/"; @@ -68,7 +61,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { super(); outputFolder = "generated-code/rust"; modelTemplateFiles.put("model.mustache", ".rs"); - apiTemplateFiles.put("api.mustache", ".rs"); modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); @@ -141,6 +133,15 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) .defaultValue(Boolean.TRUE.toString())); + supportedLibraries.put(HYPER_LIBRARY, "HTTP client: Hyper."); + supportedLibraries.put(REQWEST_LIBRARY, "HTTP client: Reqwest."); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use."); + libraryOption.setEnum(supportedLibraries); + // set hyper as the default + libraryOption.setDefault(HYPER_LIBRARY); + cliOptions.add(libraryOption); + setLibrary(HYPER_LIBRARY); } @Override @@ -165,21 +166,34 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + if ( HYPER_LIBRARY.equals(getLibrary())){ + additionalProperties.put(HYPER_LIBRARY, "true"); + } else if (REQWEST_LIBRARY.equals(getLibrary())) { + additionalProperties.put(REQWEST_LIBRARY, "true"); + } else { + LOGGER.error("Unknown library option (-l/--library): {}", getLibrary()); + } + + apiTemplateFiles.put(getLibrary() + "/api.mustache", ".rs"); + modelPackage = packageName; apiPackage = packageName; supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); - - supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs")); - supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs")); - supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs")); supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs")); - supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs")); + supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs")); supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); + + if (HYPER_LIBRARY.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs")); + } + + supportingFiles.add(new SupportingFile(getLibrary() + "/configuration.mustache", apiFolder, "configuration.rs")); + supportingFiles.add(new SupportingFile(getLibrary() + "/client.mustache", apiFolder, "client.rs")); + supportingFiles.add(new SupportingFile(getLibrary() + "/api_mod.mustache", apiFolder, "mod.rs")); } @Override @@ -209,7 +223,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { return name; // snake_case, e.g. PetId => pet_id - name = org.openapitools.codegen.utils.StringUtils.underscore(name); + name = StringUtils.underscore(name); // for reserved word or word starting with number, append _ if (isReservedWord(name)) @@ -231,16 +245,17 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { public String toModelName(String name) { // camelize the model name // phone_number => PhoneNumber - return org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name)); + return StringUtils.camelize(toModelFilename(name)); } @Override public String toModelFilename(String name) { - if (!StringUtils.isEmpty(modelNamePrefix)) { + + if (!Strings.isNullOrEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } - if (!StringUtils.isEmpty(modelNameSuffix)) { + if (!Strings.isNullOrEmpty(modelNameSuffix)) { name = name + "_" + modelNameSuffix; } @@ -258,7 +273,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } - return org.openapitools.codegen.utils.StringUtils.underscore(name); + return StringUtils.underscore(name); } @Override @@ -267,7 +282,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // e.g. PetApi.rs => pet_api.rs - return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api"; + return StringUtils.underscore(name) + "_api"; } @Override @@ -340,11 +355,11 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId)); + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + StringUtils.underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } - return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedOperationId); + return StringUtils.underscore(sanitizedOperationId); } @Override @@ -353,9 +368,15 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { Map objectMap = (Map) objs.get("operations"); @SuppressWarnings("unchecked") List operations = (List) objectMap.get("operation"); + Set headerKeys = new HashSet<>(); for (CodegenOperation operation : operations) { - // http method verb conversion (e.g. PUT => Put) - operation.httpMethod = org.openapitools.codegen.utils.StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + // http method verb conversion, depending on client library (e.g. Hyper: PUT => Put, Reqwest: PUT => put) + if (HYPER_LIBRARY.equals(getLibrary())) { + operation.httpMethod = StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + } else if (REQWEST_LIBRARY.equals(getLibrary())) { + operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT); + } + // update return type to conform to rust standard /* if (operation.returnType != null) { @@ -407,6 +428,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { }*/ } + additionalProperties.put("headerKeys", headerKeys); + additionalProperties.putIfAbsent("authHeaderKey", "api-key"); + return objs; } diff --git a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache index 6b524874aad..6fc033fe6c8 100644 --- a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache @@ -4,14 +4,21 @@ version = "{{{packageVersion}}}" authors = ["OpenAPI Generator team and contributors"] [dependencies] -serde = "1.0" -serde_derive = "1.0" -serde_yaml = "0.7" -serde_json = "1.0" -base64 = "~0.7.0" -futures = "0.1.16" -hyper = "0.11.6" +serde = "^1.0" +serde_derive = "^1.0" +serde_json = "^1.0" url = "1.5" +{{#hyper}} +hyper = "~0.11" +serde_yaml = "0.7" +base64 = "~0.7.0" +futures = "0.1.23" +{{/hyper}} +{{#reqwest}} +reqwest = "~0.9" +{{/reqwest}} [dev-dependencies] +{{#hyper}} tokio-core = "*" +{{/hyper}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/rust/README.mustache b/modules/openapi-generator/src/main/resources/rust/README.mustache index 823a371d999..712357f80fa 100644 --- a/modules/openapi-generator/src/main/resources/rust/README.mustache +++ b/modules/openapi-generator/src/main/resources/rust/README.mustache @@ -1,4 +1,4 @@ -# Rust API client for {{packageName}} +# Rust API client for {{{packageName}}} {{#appDescription}} {{{appDescription}}} @@ -7,12 +7,12 @@ ## Overview This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. -- API version: {{appVersion}} -- Package version: {{packageVersion}} +- API version: {{{appVersion}}} +- Package version: {{{packageVersion}}} {{^hideGenerationTimestamp}} -- Build date: {{generatedDate}} +- Build date: {{{generatedDate}}} {{/hideGenerationTimestamp}} -- Build package: {{generatorClass}} +- Build package: {{{generatorClass}}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) {{/infoUrl}} @@ -20,21 +20,21 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## Installation Put the package under your project folder and add the following in import: ``` - "./{{packageName}}" + "./{{{packageName}}}" ``` ## Documentation for API Endpoints -All URIs are relative to *{{basePath}}* +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}}}* | [**{{{operationId}}}**]({{{apiDocPath}}}{{classname}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} ## Documentation For Models -{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}{{{classname}}}.md) {{/model}}{{/models}} ## Documentation For Authorization @@ -92,5 +92,5 @@ Or via OAuth2 module to automatically refresh tokens and perform user authentica ## Author -{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{#apiInfo}}{{#apis}}{{^hasMore}}{{{infoEmail}}} {{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/rust/api_doc.mustache b/modules/openapi-generator/src/main/resources/rust/api_doc.mustache index 29eb3c2e5ec..c6fb6db4664 100644 --- a/modules/openapi-generator/src/main/resources/rust/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/rust/api_doc.mustache @@ -1,17 +1,17 @@ -# {{invokerPackage}}\{{classname}}{{#description}} -{{description}}{{/description}} +# {{{invokerPackage}}}\{{{classname}}}{{#description}} +{{{description}}}{{/description}} -All URIs are relative to *{{basePath}}* +All URIs are relative to *{{{basePath}}}* Method | HTTP request | Description ------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}} {{/operation}}{{/operations}} {{#operations}} {{#operation}} # **{{{operationId}}}** -> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) {{{summary}}}{{#notes}} {{{notes}}}{{/notes}} @@ -21,7 +21,7 @@ Method | HTTP request | Description Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{#authMethods}} **ctx** | **context.Context** | context containing the authentication | nil if no authentication{{/authMethods}}{{/-last}}{{/allParams}}{{#allParams}}{{#required}} - **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **{{{paramName}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}| {{{description}}} | {{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} **optional** | **map[string]interface{}** | optional parameters | nil if no parameters ### Optional Parameters @@ -29,11 +29,11 @@ Optional parameters are passed through a map[string]interface{}. {{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} - **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}} + **{{{paramName}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}| {{{description}}} | {{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{{returnBaseType}}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} ### Authorization diff --git a/modules/openapi-generator/src/main/resources/rust/api.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache similarity index 53% rename from modules/openapi-generator/src/main/resources/rust/api.mustache rename to modules/openapi-generator/src/main/resources/rust/hyper/api.mustache index 3e59a5839db..426fee7fe80 100644 --- a/modules/openapi-generator/src/main/resources/rust/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache @@ -21,20 +21,20 @@ impl {{{classname}}}Client { } } -pub trait {{classname}} { +pub trait {{{classname}}} { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>>; + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>>; {{/operation}} {{/operations}} } -impl{{classname}} for {{classname}}Client { +impl{{{classname}}} for {{{classname}}}Client { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>> { - __internal_request::Request::new(hyper::Method::{{httpMethod}}, "{{{path}}}".to_string()) + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>> { + __internal_request::Request::new(hyper::Method::{{{httpMethod}}}, "{{{path}}}".to_string()) {{#hasAuthMethods}} {{#authMethods}} {{#isApiKey}} @@ -53,29 +53,29 @@ impl{{classname}} for {{classname}}Client { {{/authMethods}} {{/hasAuthMethods}} {{#queryParams}} - .with_query_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) + .with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) {{/queryParams}} {{#pathParams}} - .with_path_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) + .with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) {{/pathParams}} {{#hasHeaderParams}} {{#headerParams}} - .with_header_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) + .with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) {{/headerParams}} {{/hasHeaderParams}} {{#hasFormParams}} {{#formParams}} {{#isFile}} - .with_form_param("{{baseName}}".to_string(), unimplemented!()) + .with_form_param("{{{baseName}}}".to_string(), unimplemented!()) {{/isFile}} {{^isFile}} - .with_form_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) + .with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) {{/isFile}} {{/formParams}} {{/hasFormParams}} {{#hasBodyParam}} {{#bodyParams}} - .with_body_param({{paramName}}) + .with_body_param({{{paramName}}}) {{/bodyParams}} {{/hasBodyParam}} {{^returnType}} diff --git a/modules/openapi-generator/src/main/resources/rust/api_mod.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache similarity index 92% rename from modules/openapi-generator/src/main/resources/rust/api_mod.mustache rename to modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache index 1f587b0d52f..1deca998a0d 100644 --- a/modules/openapi-generator/src/main/resources/rust/api_mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache @@ -55,11 +55,11 @@ mod request; {{#apiInfo}} {{#apis}} -mod {{classFilename}}; +mod {{{classFilename}}}; {{#operations}} {{#operation}} {{#-last}} -pub use self::{{classFilename}}::{ {{classname}}, {{classname}}Client }; +pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; {{/-last}} {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/rust/client.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache similarity index 76% rename from modules/openapi-generator/src/main/resources/rust/client.mustache rename to modules/openapi-generator/src/main/resources/rust/hyper/client.mustache index faaea0dbd2f..71b31ccc993 100644 --- a/modules/openapi-generator/src/main/resources/rust/client.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache @@ -10,7 +10,7 @@ pub struct APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box<::apis::{{classname}}>, + {{{classFilename}}}: Box<::apis::{{{classname}}}>, {{/-last}} {{/operation}} {{/operations}} @@ -29,7 +29,7 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box::new(::apis::{{classname}}Client::new(rc.clone())), + {{{classFilename}}}: Box::new(::apis::{{{classname}}}Client::new(rc.clone())), {{/-last}} {{/operation}} {{/operations}} @@ -43,8 +43,8 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - pub fn {{classFilename}}(&self) -> &::apis::{{classname}}{ - self.{{classFilename}}.as_ref() + pub fn {{{classFilename}}}(&self) -> &::apis::{{{classname}}}{ + self.{{{classFilename}}}.as_ref() } {{/-last}} diff --git a/modules/openapi-generator/src/main/resources/rust/configuration.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache similarity index 88% rename from modules/openapi-generator/src/main/resources/rust/configuration.mustache rename to modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache index a30f5014e35..8c273278d6b 100644 --- a/modules/openapi-generator/src/main/resources/rust/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache @@ -23,7 +23,7 @@ impl Configuration { pub fn new(client: hyper::client::Client) -> Configuration { Configuration { base_path: "{{{basePath}}}".to_owned(), - user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{version}}/rust".to_owned()){{/httpUserAgent}}, + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, client: client, basic_auth: None, oauth_access_token: None, diff --git a/modules/openapi-generator/src/main/resources/rust/lib.mustache b/modules/openapi-generator/src/main/resources/rust/lib.mustache new file mode 100644 index 00000000000..cdc5287aae7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust/lib.mustache @@ -0,0 +1,16 @@ +#[macro_use] +extern crate serde_derive; + +extern crate serde; +extern crate serde_json; +extern crate url; +{{#hyper}} +extern crate hyper; +extern crate futures; +{{/hyper}} +{{#reqwest}} +extern crate reqwest; +{{/reqwest}} + +pub mod apis; +pub mod models; diff --git a/modules/openapi-generator/src/main/resources/rust/model.mustache b/modules/openapi-generator/src/main/resources/rust/model.mustache index afb557c3410..6c86c531d36 100644 --- a/modules/openapi-generator/src/main/resources/rust/model.mustache +++ b/modules/openapi-generator/src/main/resources/rust/model.mustache @@ -9,45 +9,45 @@ use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] -pub struct {{classname}} { +pub struct {{{classname}}} { {{#vars}} {{#description}} /// {{{description}}} {{/description}} - #[serde(rename = "{{baseName}}")] - {{name}}: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} + #[serde(rename = "{{{baseName}}}")] + {{{name}}}: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } -impl {{classname}} { +impl {{{classname}}} { {{#description}} /// {{{description}}} {{/description}} - pub fn new({{#requiredVars}}{{name}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { - {{classname}} { + pub fn new({{#requiredVars}}{{{name}}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { + {{{classname}}} { {{#vars}} - {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{{name}}}: {{#required}}{{{name}}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } } {{#vars}} - pub fn set_{{name}}(&mut self, {{name}}: {{{dataType}}}) { - self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + pub fn set_{{{name}}}(&mut self, {{{name}}}: {{{dataType}}}) { + self.{{{name}}} = {{^required}}Some({{{name}}}){{/required}}{{#required}}{{{name}}}{{/required}}; } - pub fn with_{{name}}(mut self, {{name}}: {{{dataType}}}) -> {{classname}} { - self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + pub fn with_{{{name}}}(mut self, {{{name}}}: {{{dataType}}}) -> {{{classname}}} { + self.{{{name}}} = {{^required}}Some({{{name}}}){{/required}}{{#required}}{{{name}}}{{/required}}; self } - pub fn {{name}}(&self) -> {{^required}}Option<{{/required}}&{{{dataType}}}{{^required}}>{{/required}} { - {{#required}}&{{/required}}self.{{name}}{{^required}}.as_ref(){{/required}} + pub fn {{{name}}}(&self) -> {{^required}}Option<{{/required}}&{{{dataType}}}{{^required}}>{{/required}} { + {{#required}}&{{/required}}self.{{{name}}}{{^required}}.as_ref(){{/required}} } {{^required}} - pub fn reset_{{name}}(&mut self) { - self.{{name}} = None; + pub fn reset_{{{name}}}(&mut self) { + self.{{{name}}} = None; } {{/required}} @@ -60,7 +60,7 @@ impl {{classname}} { //const ( // {{#allowableValues}} // {{#enumVars}} -// {{name}} {{{classname}}} = "{{{value}}}" +// {{{name}}} {{{classname}}} = "{{{value}}}" // {{/enumVars}} // {{/allowableValues}} //) diff --git a/modules/openapi-generator/src/main/resources/rust/model_doc.mustache b/modules/openapi-generator/src/main/resources/rust/model_doc.mustache index ccfd3f8d0de..aeaeb959166 100644 --- a/modules/openapi-generator/src/main/resources/rust/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/rust/model_doc.mustache @@ -1,9 +1,9 @@ -{{#models}}{{#model}}# {{classname}} +{{#models}}{{#model}}# {{{classname}}} ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{#vars}}**{{{name}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#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/rust/reqwest/api.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache new file mode 100644 index 00000000000..091c40fe625 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache @@ -0,0 +1,113 @@ +{{>partial_header}} +use std::rc::Rc; +use std::borrow::Borrow; + +use reqwest; + +use super::{Error, configuration}; + +pub struct {{{classname}}}Client { + configuration: Rc, +} + +impl {{{classname}}}Client { + pub fn new(configuration: Rc) -> {{{classname}}}Client { + {{{classname}}}Client { + configuration: configuration, + } + } +} + +pub trait {{{classname}}} { +{{#operations}} +{{#operation}} + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>; +{{/operation}} +{{/operations}} +} + + +impl {{{classname}}} for {{{classname}}}Client { +{{#operations}} +{{#operation}} + fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); +{{#queryParams}} + query.append_pair("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isListContainer}}.to_string()); +{{/queryParams}} +{{#hasAuthMethods}}{{#authMethods}}{{#isApiKey}}{{#isKeyInQuery}} + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + query.append_pair("{{{keyParamName}}}".to_owned(), val); + } +{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}}{{/hasAuthMethods}} + query.finish() + }; + let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{{baseName}}}={{{paramName}}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); + + let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + {{#hasHeaderParams}} + {{#headerParams}} + req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + {{/headerParams}} + {{/hasHeaderParams}} + + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}}{{#isKeyInHeader}} + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("{{{keyParamName}}}", val); + }; + {{/isKeyInHeader}}{{/isApiKey}} + {{#isBasic}} + if let Some(ref auth_conf) = configuration.basic_auth { + req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned()); + }; + {{/isBasic}} + {{#isOAuth}} + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + {{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{#hasBodyParam}} + {{#bodyParams}} + req_builder = req_builder.json(&{{{paramName}}}); + {{/bodyParams}} + {{/hasBodyParam}} + + // send request + let req = req_builder.build()?; + + {{^returnType}} + client.execute(req)?.error_for_status()?; + Ok(()) + {{/returnType}} + {{#returnType}} + Ok(client.execute(req)?.error_for_status()?.json()?) + {{/returnType}} + } + +{{/operation}} +{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache new file mode 100644 index 00000000000..483e2c388f8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache @@ -0,0 +1,38 @@ +use reqwest; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + Serde(serde_json::Error), +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + return Error::Reqwest(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + return Error::Serde(e) + } +} + +use super::models::*; + +{{#apiInfo}} +{{#apis}} +mod {{{classFilename}}}; +{{#operations}} +{{#operation}} +{{#-last}} +pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client }; +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +pub mod configuration; +pub mod client; diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/client.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/client.mustache new file mode 100644 index 00000000000..61765226a26 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/client.mustache @@ -0,0 +1,55 @@ +use std::rc::Rc; + +use super::configuration::Configuration; + +pub struct APIClient { + configuration: Rc, +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box<::apis::{{{classname}}}>, + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient { + let rc = Rc::new(configuration); + + APIClient { + configuration: rc.clone(), +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{{classFilename}}}: Box::new(::apis::{{{classname}}}Client::new(rc.clone())), + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + } + } + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#-last}} + pub fn {{{classFilename}}}(&self) -> &::apis::{{{classname}}}{ + self.{{{classFilename}}}.as_ref() + } + +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +} diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache new file mode 100644 index 00000000000..c50ff814e5d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache @@ -0,0 +1,39 @@ +{{>partial_header}} + +use reqwest; + +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: reqwest::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("Swagger-Codegen/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client: reqwest::Client::new(), + basic_auth: None, + oauth_access_token: None, + api_key: None, + } + } +} diff --git a/pom.xml b/pom.xml index 785535523e7..e6e229d0c19 100644 --- a/pom.xml +++ b/pom.xml @@ -1025,6 +1025,7 @@ samples/client/petstore/elm-0.18 samples/client/petstore/groovy samples/client/petstore/rust + samples/client/petstore/rust-reqwest samples/client/petstore/php/OpenAPIClient-php samples/openapi3/client/petstore/php/OpenAPIClient-php diff --git a/samples/client/petstore/rust-reqwest/.gitignore b/samples/client/petstore/rust-reqwest/.gitignore new file mode 100644 index 00000000000..6aa106405a4 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/samples/client/petstore/rust-reqwest/.openapi-generator-ignore b/samples/client/petstore/rust-reqwest/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/.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/rust-reqwest/.openapi-generator/VERSION b/samples/client/petstore/rust-reqwest/.openapi-generator/VERSION new file mode 100644 index 00000000000..a6527129083 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/.openapi-generator/VERSION @@ -0,0 +1 @@ +3.3.2-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust-reqwest/.travis.yml b/samples/client/petstore/rust-reqwest/.travis.yml new file mode 100644 index 00000000000..22761ba7ee1 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/samples/client/petstore/rust-reqwest/Cargo.toml b/samples/client/petstore/rust-reqwest/Cargo.toml new file mode 100644 index 00000000000..6d66b8f7c7c --- /dev/null +++ b/samples/client/petstore/rust-reqwest/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "petstore_client" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] + +[dependencies] +serde = "^1.0" +serde_derive = "^1.0" +serde_json = "^1.0" +url = "1.5" +reqwest = "~0.9" + +[dev-dependencies] diff --git a/samples/client/petstore/rust-reqwest/README.md b/samples/client/petstore/rust-reqwest/README.md new file mode 100644 index 00000000000..9d256c59927 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/README.md @@ -0,0 +1,97 @@ +# Rust API client for petstore_client + +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 API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RustClientCodegen + +## Installation +Put the package under your project folder and add the following in import: +``` + "./petstore_client" +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*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 +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **delete** /store/order/{orderId} | 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/{orderId} | 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 + + - [ApiResponse](docs/ApiResponse.md) + - [Category](docs/Category.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation For Authorization + +## api_key +- **Type**: API key + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` +## 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 + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automatically refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` + +## Author + + + diff --git a/samples/client/petstore/rust-reqwest/docs/ApiResponse.md b/samples/client/petstore/rust-reqwest/docs/ApiResponse.md new file mode 100644 index 00000000000..3af9a16ab36 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **i32** | | [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/rust-reqwest/docs/Category.md b/samples/client/petstore/rust-reqwest/docs/Category.md new file mode 100644 index 00000000000..39aaee2b052 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [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/rust-reqwest/docs/Order.md b/samples/client/petstore/rust-reqwest/docs/Order.md new file mode 100644 index 00000000000..f350a8b5b4e --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] +**pet_id** | **i64** | | [optional] +**quantity** | **i32** | | [optional] +**ship_date** | **String** | | [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/rust-reqwest/docs/Pet.md b/samples/client/petstore/rust-reqwest/docs/Pet.md new file mode 100644 index 00000000000..097c4390288 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] +**category** | [***::models::Category**](Category.md) | | [optional] +**name** | **String** | | +**photo_urls** | **Vec** | | +**tags** | [**Vec<::models::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/client/petstore/rust-reqwest/docs/PetApi.md b/samples/client/petstore/rust-reqwest/docs/PetApi.md new file mode 100644 index 00000000000..ea3b5825627 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/PetApi.md @@ -0,0 +1,259 @@ +# \PetApi + +All URIs are relative to *http://petstore.swagger.io/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 + + +# **add_pet** +> add_pet(ctx, pet) +Add a new pet to the store + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + + (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) + +# **delete_pet** +> delete_pet(ctx, pet_id, optional) +Deletes a pet + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| Pet id to delete | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| Pet id to delete | + **api_key** | **String**| | + +### Return type + + (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) + +# **find_pets_by_status** +> Vec<::models::Pet> find_pets_by_status(ctx, status) +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **status** | [**Vec**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**Vec<::models::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) + +# **find_pets_by_tags** +> Vec<::models::Pet> find_pets_by_tags(ctx, tags) +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **tags** | [**Vec**](String.md)| Tags to filter by | + +### Return type + +[**Vec<::models::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) + +# **get_pet_by_id** +> ::models::Pet get_pet_by_id(ctx, pet_id) +Find pet by ID + +Returns a single pet + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet to return | + +### Return type + +[**::models::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) + +# **update_pet** +> update_pet(ctx, pet) +Update an existing pet + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + + (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) + +# **update_pet_with_form** +> update_pet_with_form(ctx, pet_id, optional) +Updates a pet in the store with form data + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet that needs to be updated | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | + **status** | **String**| Updated status of the pet | + +### Return type + + (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) + +# **upload_file** +> ::models::ApiResponse upload_file(ctx, pet_id, optional) +uploads an image + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet to update | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| ID of pet to update | + **additional_metadata** | **String**| Additional data to pass to server | + **file** | **::models::File**| file to upload | + +### Return type + +[**::models::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/rust-reqwest/docs/StoreApi.md b/samples/client/petstore/rust-reqwest/docs/StoreApi.md new file mode 100644 index 00000000000..a4555a25565 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/StoreApi.md @@ -0,0 +1,115 @@ +# \StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **delete** /store/order/{orderId} | 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/{orderId} | 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 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **String**| ID of the order that needs to be deleted | + +### Return type + + (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) + +# **get_inventory** +> ::std::collections::HashMap get_inventory(ctx, ) +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + +**::std::collections::HashMap** + +### 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) + +# **get_order_by_id** +> ::models::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 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **i64**| ID of pet that needs to be fetched | + +### Return type + +[**::models::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) + +# **place_order** +> ::models::Order place_order(order) +Place an order for a pet + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**::models::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/rust-reqwest/docs/Tag.md b/samples/client/petstore/rust-reqwest/docs/Tag.md new file mode 100644 index 00000000000..d1118479b90 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [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/rust-reqwest/docs/User.md b/samples/client/petstore/rust-reqwest/docs/User.md new file mode 100644 index 00000000000..33aa9693902 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] +**username** | **String** | | [optional] +**first_name** | **String** | | [optional] +**last_name** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**user_status** | **i32** | 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/rust-reqwest/docs/UserApi.md b/samples/client/petstore/rust-reqwest/docs/UserApi.md new file mode 100644 index 00000000000..05d2aeccaa3 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/docs/UserApi.md @@ -0,0 +1,221 @@ +# \UserApi + +All URIs are relative to *http://petstore.swagger.io/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(user) +Create user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + + (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) + +# **create_users_with_array_input** +> create_users_with_array_input(user) +Creates list of users with given input array + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**Vec<::models::User>**](array.md)| List of user object | + +### Return type + + (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) + +# **create_users_with_list_input** +> create_users_with_list_input(user) +Creates list of users with given input array + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**Vec<::models::User>**](array.md)| List of user object | + +### Return type + + (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) + +# **delete_user** +> delete_user(username) +Delete user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + + (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) + +# **get_user_by_name** +> ::models::User get_user_by_name(username) +Get user by user name + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**::models::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) + +# **login_user** +> String login_user(username, password) +Logs user into the system + +### Required 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) + +# **logout_user** +> logout_user() +Logs out current logged in user session + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + + (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) + +# **update_user** +> update_user(username, user) +Updated user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + + (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/rust-reqwest/git_push.sh b/samples/client/petstore/rust-reqwest/git_push.sh new file mode 100644 index 00000000000..8442b80bb44 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/git_push.sh @@ -0,0 +1,52 @@ +#!/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" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +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://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${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://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/rust-reqwest/pom.xml b/samples/client/petstore/rust-reqwest/pom.xml new file mode 100644 index 00000000000..299a9058f7c --- /dev/null +++ b/samples/client/petstore/rust-reqwest/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + RustReqwestPetstoreClientTests + pom + 1.0-SNAPSHOT + Rust Reqwest Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-test + integration-test + + exec + + + cargo + + check + + + + + + + + diff --git a/samples/client/petstore/rust-reqwest/src/apis/client.rs b/samples/client/petstore/rust-reqwest/src/apis/client.rs new file mode 100644 index 00000000000..4b4f29ce08b --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/client.rs @@ -0,0 +1,37 @@ +use std::rc::Rc; + +use super::configuration::Configuration; + +pub struct APIClient { + configuration: Rc, + pet_api: Box<::apis::PetApi>, + store_api: Box<::apis::StoreApi>, + user_api: Box<::apis::UserApi>, +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient { + let rc = Rc::new(configuration); + + APIClient { + configuration: rc.clone(), + pet_api: Box::new(::apis::PetApiClient::new(rc.clone())), + store_api: Box::new(::apis::StoreApiClient::new(rc.clone())), + user_api: Box::new(::apis::UserApiClient::new(rc.clone())), + } + } + + pub fn pet_api(&self) -> &::apis::PetApi{ + self.pet_api.as_ref() + } + + pub fn store_api(&self) -> &::apis::StoreApi{ + self.store_api.as_ref() + } + + pub fn user_api(&self) -> &::apis::UserApi{ + self.user_api.as_ref() + } + + +} diff --git a/samples/client/petstore/rust-reqwest/src/apis/configuration.rs b/samples/client/petstore/rust-reqwest/src/apis/configuration.rs new file mode 100644 index 00000000000..c6c5ee8519b --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/configuration.rs @@ -0,0 +1,48 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: reqwest::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "http://petstore.swagger.io/v2".to_owned(), + user_agent: Some("Swagger-Codegen/1.0.0/rust".to_owned()), + client: reqwest::Client::new(), + basic_auth: None, + oauth_access_token: None, + api_key: None, + } + } +} diff --git a/samples/client/petstore/rust-reqwest/src/apis/mod.rs b/samples/client/petstore/rust-reqwest/src/apis/mod.rs new file mode 100644 index 00000000000..7494e25ce9e --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/mod.rs @@ -0,0 +1,32 @@ +use reqwest; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + Serde(serde_json::Error), +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + return Error::Reqwest(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + return Error::Serde(e) + } +} + +use super::models::*; + +mod pet_api; +pub use self::pet_api::{ PetApi, PetApiClient }; +mod store_api; +pub use self::store_api::{ StoreApi, StoreApiClient }; +mod user_api; +pub use self::user_api::{ UserApi, UserApiClient }; + +pub mod configuration; +pub mod client; diff --git a/samples/client/petstore/rust-reqwest/src/apis/pet_api.rs b/samples/client/petstore/rust-reqwest/src/apis/pet_api.rs new file mode 100644 index 00000000000..7771c6568d6 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/pet_api.rs @@ -0,0 +1,298 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use std::rc::Rc; +use std::borrow::Borrow; + +use reqwest; + +use super::{Error, configuration}; + +pub struct PetApiClient { + configuration: Rc, +} + +impl PetApiClient { + pub fn new(configuration: Rc) -> PetApiClient { + PetApiClient { + configuration: configuration, + } + } +} + +pub trait PetApi { + fn add_pet(&self, pet: ::models::Pet) -> Result<(), Error>; + fn delete_pet(&self, pet_id: i64, api_key: &str) -> Result<(), Error>; + fn find_pets_by_status(&self, status: Vec) -> Result, Error>; + fn find_pets_by_tags(&self, tags: Vec) -> Result, Error>; + fn get_pet_by_id(&self, pet_id: i64) -> Result<::models::Pet, Error>; + fn update_pet(&self, pet: ::models::Pet) -> Result<(), Error>; + fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Result<(), Error>; + fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Result<::models::ApiResponse, Error>; +} + + +impl PetApi for PetApiClient { + fn add_pet(&self, pet: ::models::Pet) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet?{}", configuration.base_path, query_string); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + req_builder = req_builder.json(&pet); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn delete_pet(&self, pet_id: i64, api_key: &str) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); + + let mut req_builder = client.delete(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + req_builder = req_builder.header("api_key", api_key.to_string()); + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn find_pets_by_status(&self, status: Vec) -> Result, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string()); + + query.finish() + }; + let uri_str = format!("{}/pet/findByStatus?{}", configuration.base_path, query_string); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn find_pets_by_tags(&self, tags: Vec) -> Result, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string()); + + query.finish() + }; + let uri_str = format!("{}/pet/findByTags?{}", configuration.base_path, query_string); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn get_pet_by_id(&self, pet_id: i64) -> Result<::models::Pet, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("api_key", val); + }; + + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn update_pet(&self, pet: ::models::Pet) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet?{}", configuration.base_path, query_string); + + let mut req_builder = client.put(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + req_builder = req_builder.json(&pet); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Result<::models::ApiResponse, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/pet/{petId}/uploadImage?{}", configuration.base_path, query_string, petId=pet_id); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + +} diff --git a/samples/client/petstore/rust-reqwest/src/apis/store_api.rs b/samples/client/petstore/rust-reqwest/src/apis/store_api.rs new file mode 100644 index 00000000000..90a719df929 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/store_api.rs @@ -0,0 +1,155 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use std::rc::Rc; +use std::borrow::Borrow; + +use reqwest; + +use super::{Error, configuration}; + +pub struct StoreApiClient { + configuration: Rc, +} + +impl StoreApiClient { + pub fn new(configuration: Rc) -> StoreApiClient { + StoreApiClient { + configuration: configuration, + } + } +} + +pub trait StoreApi { + fn delete_order(&self, order_id: &str) -> Result<(), Error>; + fn get_inventory(&self, ) -> Result<::std::collections::HashMap, Error>; + fn get_order_by_id(&self, order_id: i64) -> Result<::models::Order, Error>; + fn place_order(&self, order: ::models::Order) -> Result<::models::Order, Error>; +} + + +impl StoreApi for StoreApiClient { + fn delete_order(&self, order_id: &str) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id); + + let mut req_builder = client.delete(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn get_inventory(&self, ) -> Result<::std::collections::HashMap, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/store/inventory?{}", configuration.base_path, query_string); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let val = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("api_key", val); + }; + + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn get_order_by_id(&self, order_id: i64) -> Result<::models::Order, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn place_order(&self, order: ::models::Order) -> Result<::models::Order, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/store/order?{}", configuration.base_path, query_string); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + req_builder = req_builder.json(&order); + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + +} diff --git a/samples/client/petstore/rust-reqwest/src/apis/user_api.rs b/samples/client/petstore/rust-reqwest/src/apis/user_api.rs new file mode 100644 index 00000000000..8d14e2dc5ce --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/apis/user_api.rs @@ -0,0 +1,263 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use std::rc::Rc; +use std::borrow::Borrow; + +use reqwest; + +use super::{Error, configuration}; + +pub struct UserApiClient { + configuration: Rc, +} + +impl UserApiClient { + pub fn new(configuration: Rc) -> UserApiClient { + UserApiClient { + configuration: configuration, + } + } +} + +pub trait UserApi { + fn create_user(&self, user: ::models::User) -> Result<(), Error>; + fn create_users_with_array_input(&self, user: Vec<::models::User>) -> Result<(), Error>; + fn create_users_with_list_input(&self, user: Vec<::models::User>) -> Result<(), Error>; + fn delete_user(&self, username: &str) -> Result<(), Error>; + fn get_user_by_name(&self, username: &str) -> Result<::models::User, Error>; + fn login_user(&self, username: &str, password: &str) -> Result; + fn logout_user(&self, ) -> Result<(), Error>; + fn update_user(&self, username: &str, user: ::models::User) -> Result<(), Error>; +} + + +impl UserApi for UserApiClient { + fn create_user(&self, user: ::models::User) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user?{}", configuration.base_path, query_string); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + req_builder = req_builder.json(&user); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn create_users_with_array_input(&self, user: Vec<::models::User>) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/createWithArray?{}", configuration.base_path, query_string); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + req_builder = req_builder.json(&user); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn create_users_with_list_input(&self, user: Vec<::models::User>) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/createWithList?{}", configuration.base_path, query_string); + + let mut req_builder = client.post(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + req_builder = req_builder.json(&user); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn delete_user(&self, username: &str) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); + + let mut req_builder = client.delete(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn get_user_by_name(&self, username: &str) -> Result<::models::User, Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn login_user(&self, username: &str, password: &str) -> Result { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + query.append_pair("username", &username.to_string()); + query.append_pair("password", &password.to_string()); + + query.finish() + }; + let uri_str = format!("{}/user/login?{}", configuration.base_path, query_string); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + Ok(client.execute(req)?.error_for_status()?.json()?) + } + + fn logout_user(&self, ) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/logout?{}", configuration.base_path, query_string); + + let mut req_builder = client.get(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + + fn update_user(&self, username: &str, user: ::models::User) -> Result<(), Error> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let client = &configuration.client; + + let query_string = { + let mut query = ::url::form_urlencoded::Serializer::new(String::new()); + + query.finish() + }; + let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username); + + let mut req_builder = client.put(uri_str.as_str()); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + + + req_builder = req_builder.json(&user); + + // send request + let req = req_builder.build()?; + + client.execute(req)?.error_for_status()?; + Ok(()) + } + +} diff --git a/modules/openapi-generator/src/main/resources/rust/lib.rs b/samples/client/petstore/rust-reqwest/src/lib.rs similarity index 76% rename from modules/openapi-generator/src/main/resources/rust/lib.rs rename to samples/client/petstore/rust-reqwest/src/lib.rs index b51fea8150e..c1dd666f795 100644 --- a/modules/openapi-generator/src/main/resources/rust/lib.rs +++ b/samples/client/petstore/rust-reqwest/src/lib.rs @@ -1,11 +1,10 @@ #[macro_use] extern crate serde_derive; -extern crate hyper; extern crate serde; extern crate serde_json; -extern crate futures; extern crate url; +extern crate reqwest; pub mod apis; pub mod models; diff --git a/samples/client/petstore/rust-reqwest/src/models/api_response.rs b/samples/client/petstore/rust-reqwest/src/models/api_response.rs new file mode 100644 index 00000000000..0c9de96d442 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/api_response.rs @@ -0,0 +1,90 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// ApiResponse : Describes the result of uploading an image resource + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct ApiResponse { + #[serde(rename = "code")] + code: Option, + #[serde(rename = "type")] + _type: Option, + #[serde(rename = "message")] + message: Option +} + +impl ApiResponse { + /// Describes the result of uploading an image resource + pub fn new() -> ApiResponse { + ApiResponse { + code: None, + _type: None, + message: None + } + } + + pub fn set_code(&mut self, code: i32) { + self.code = Some(code); + } + + pub fn with_code(mut self, code: i32) -> ApiResponse { + self.code = Some(code); + self + } + + pub fn code(&self) -> Option<&i32> { + self.code.as_ref() + } + + pub fn reset_code(&mut self) { + self.code = None; + } + + pub fn set__type(&mut self, _type: String) { + self._type = Some(_type); + } + + pub fn with__type(mut self, _type: String) -> ApiResponse { + self._type = Some(_type); + self + } + + pub fn _type(&self) -> Option<&String> { + self._type.as_ref() + } + + pub fn reset__type(&mut self) { + self._type = None; + } + + pub fn set_message(&mut self, message: String) { + self.message = Some(message); + } + + pub fn with_message(mut self, message: String) -> ApiResponse { + self.message = Some(message); + self + } + + pub fn message(&self) -> Option<&String> { + self.message.as_ref() + } + + pub fn reset_message(&mut self) { + self.message = None; + } + +} + + + diff --git a/samples/client/petstore/rust-reqwest/src/models/category.rs b/samples/client/petstore/rust-reqwest/src/models/category.rs new file mode 100644 index 00000000000..5a9e1b98366 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/category.rs @@ -0,0 +1,70 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Category : A category for a pet + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Category { + #[serde(rename = "id")] + id: Option, + #[serde(rename = "name")] + name: Option +} + +impl Category { + /// A category for a pet + pub fn new() -> Category { + Category { + id: None, + name: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Category { + self.id = Some(id); + self + } + + pub fn id(&self) -> Option<&i64> { + self.id.as_ref() + } + + pub fn reset_id(&mut self) { + self.id = None; + } + + pub fn set_name(&mut self, name: String) { + self.name = Some(name); + } + + pub fn with_name(mut self, name: String) -> Category { + self.name = Some(name); + self + } + + pub fn name(&self) -> Option<&String> { + self.name.as_ref() + } + + pub fn reset_name(&mut self) { + self.name = None; + } + +} + + + diff --git a/samples/client/petstore/rust-reqwest/src/models/mod.rs b/samples/client/petstore/rust-reqwest/src/models/mod.rs new file mode 100644 index 00000000000..b24024670b2 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/mod.rs @@ -0,0 +1,15 @@ +mod api_response; +pub use self::api_response::ApiResponse; +mod category; +pub use self::category::Category; +mod order; +pub use self::order::Order; +mod pet; +pub use self::pet::Pet; +mod tag; +pub use self::tag::Tag; +mod user; +pub use self::user::User; + +// TODO(farcaller): sort out files +pub struct File; diff --git a/samples/client/petstore/rust-reqwest/src/models/order.rs b/samples/client/petstore/rust-reqwest/src/models/order.rs new file mode 100644 index 00000000000..1e88b0beced --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/order.rs @@ -0,0 +1,151 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Order : An order for a pets from the pet store + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Order { + #[serde(rename = "id")] + id: Option, + #[serde(rename = "petId")] + pet_id: Option, + #[serde(rename = "quantity")] + quantity: Option, + #[serde(rename = "shipDate")] + ship_date: Option, + /// Order Status + #[serde(rename = "status")] + status: Option, + #[serde(rename = "complete")] + complete: Option +} + +impl Order { + /// An order for a pets from the pet store + pub fn new() -> Order { + Order { + id: None, + pet_id: None, + quantity: None, + ship_date: None, + status: None, + complete: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Order { + self.id = Some(id); + self + } + + pub fn id(&self) -> Option<&i64> { + self.id.as_ref() + } + + pub fn reset_id(&mut self) { + self.id = None; + } + + pub fn set_pet_id(&mut self, pet_id: i64) { + self.pet_id = Some(pet_id); + } + + pub fn with_pet_id(mut self, pet_id: i64) -> Order { + self.pet_id = Some(pet_id); + self + } + + pub fn pet_id(&self) -> Option<&i64> { + self.pet_id.as_ref() + } + + pub fn reset_pet_id(&mut self) { + self.pet_id = None; + } + + pub fn set_quantity(&mut self, quantity: i32) { + self.quantity = Some(quantity); + } + + pub fn with_quantity(mut self, quantity: i32) -> Order { + self.quantity = Some(quantity); + self + } + + pub fn quantity(&self) -> Option<&i32> { + self.quantity.as_ref() + } + + pub fn reset_quantity(&mut self) { + self.quantity = None; + } + + pub fn set_ship_date(&mut self, ship_date: String) { + self.ship_date = Some(ship_date); + } + + pub fn with_ship_date(mut self, ship_date: String) -> Order { + self.ship_date = Some(ship_date); + self + } + + pub fn ship_date(&self) -> Option<&String> { + self.ship_date.as_ref() + } + + pub fn reset_ship_date(&mut self) { + self.ship_date = None; + } + + pub fn set_status(&mut self, status: String) { + self.status = Some(status); + } + + pub fn with_status(mut self, status: String) -> Order { + self.status = Some(status); + self + } + + pub fn status(&self) -> Option<&String> { + self.status.as_ref() + } + + pub fn reset_status(&mut self) { + self.status = None; + } + + pub fn set_complete(&mut self, complete: bool) { + self.complete = Some(complete); + } + + pub fn with_complete(mut self, complete: bool) -> Order { + self.complete = Some(complete); + self + } + + pub fn complete(&self) -> Option<&bool> { + self.complete.as_ref() + } + + pub fn reset_complete(&mut self) { + self.complete = None; + } + +} + + + diff --git a/samples/client/petstore/rust-reqwest/src/models/pet.rs b/samples/client/petstore/rust-reqwest/src/models/pet.rs new file mode 100644 index 00000000000..6407103eeb1 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/pet.rs @@ -0,0 +1,145 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Pet : A pet for sale in the pet store + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Pet { + #[serde(rename = "id")] + id: Option, + #[serde(rename = "category")] + category: Option<::models::Category>, + #[serde(rename = "name")] + name: String, + #[serde(rename = "photoUrls")] + photo_urls: Vec, + #[serde(rename = "tags")] + tags: Option>, + /// pet status in the store + #[serde(rename = "status")] + status: Option +} + +impl Pet { + /// A pet for sale in the pet store + pub fn new(name: String, photo_urls: Vec) -> Pet { + Pet { + id: None, + category: None, + name: name, + photo_urls: photo_urls, + tags: None, + status: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Pet { + self.id = Some(id); + self + } + + pub fn id(&self) -> Option<&i64> { + self.id.as_ref() + } + + pub fn reset_id(&mut self) { + self.id = None; + } + + pub fn set_category(&mut self, category: ::models::Category) { + self.category = Some(category); + } + + pub fn with_category(mut self, category: ::models::Category) -> Pet { + self.category = Some(category); + self + } + + pub fn category(&self) -> Option<&::models::Category> { + self.category.as_ref() + } + + pub fn reset_category(&mut self) { + self.category = None; + } + + pub fn set_name(&mut self, name: String) { + self.name = name; + } + + pub fn with_name(mut self, name: String) -> Pet { + self.name = name; + self + } + + pub fn name(&self) -> &String { + &self.name + } + + + pub fn set_photo_urls(&mut self, photo_urls: Vec) { + self.photo_urls = photo_urls; + } + + pub fn with_photo_urls(mut self, photo_urls: Vec) -> Pet { + self.photo_urls = photo_urls; + self + } + + pub fn photo_urls(&self) -> &Vec { + &self.photo_urls + } + + + pub fn set_tags(&mut self, tags: Vec<::models::Tag>) { + self.tags = Some(tags); + } + + pub fn with_tags(mut self, tags: Vec<::models::Tag>) -> Pet { + self.tags = Some(tags); + self + } + + pub fn tags(&self) -> Option<&Vec<::models::Tag>> { + self.tags.as_ref() + } + + pub fn reset_tags(&mut self) { + self.tags = None; + } + + pub fn set_status(&mut self, status: String) { + self.status = Some(status); + } + + pub fn with_status(mut self, status: String) -> Pet { + self.status = Some(status); + self + } + + pub fn status(&self) -> Option<&String> { + self.status.as_ref() + } + + pub fn reset_status(&mut self) { + self.status = None; + } + +} + + + diff --git a/samples/client/petstore/rust-reqwest/src/models/tag.rs b/samples/client/petstore/rust-reqwest/src/models/tag.rs new file mode 100644 index 00000000000..a698451706b --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/tag.rs @@ -0,0 +1,70 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Tag : A tag for a pet + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Tag { + #[serde(rename = "id")] + id: Option, + #[serde(rename = "name")] + name: Option +} + +impl Tag { + /// A tag for a pet + pub fn new() -> Tag { + Tag { + id: None, + name: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Tag { + self.id = Some(id); + self + } + + pub fn id(&self) -> Option<&i64> { + self.id.as_ref() + } + + pub fn reset_id(&mut self) { + self.id = None; + } + + pub fn set_name(&mut self, name: String) { + self.name = Some(name); + } + + pub fn with_name(mut self, name: String) -> Tag { + self.name = Some(name); + self + } + + pub fn name(&self) -> Option<&String> { + self.name.as_ref() + } + + pub fn reset_name(&mut self) { + self.name = None; + } + +} + + + diff --git a/samples/client/petstore/rust-reqwest/src/models/user.rs b/samples/client/petstore/rust-reqwest/src/models/user.rs new file mode 100644 index 00000000000..6c83a23e250 --- /dev/null +++ b/samples/client/petstore/rust-reqwest/src/models/user.rs @@ -0,0 +1,191 @@ +/* + * 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. + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// User : A User who is purchasing from the pet store + +#[allow(unused_imports)] +use serde_json::Value; + +#[derive(Debug, Serialize, Deserialize)] +pub struct User { + #[serde(rename = "id")] + id: Option, + #[serde(rename = "username")] + username: Option, + #[serde(rename = "firstName")] + first_name: Option, + #[serde(rename = "lastName")] + last_name: Option, + #[serde(rename = "email")] + email: Option, + #[serde(rename = "password")] + password: Option, + #[serde(rename = "phone")] + phone: Option, + /// User Status + #[serde(rename = "userStatus")] + user_status: Option +} + +impl User { + /// A User who is purchasing from the pet store + pub fn new() -> User { + User { + id: None, + username: None, + first_name: None, + last_name: None, + email: None, + password: None, + phone: None, + user_status: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> User { + self.id = Some(id); + self + } + + pub fn id(&self) -> Option<&i64> { + self.id.as_ref() + } + + pub fn reset_id(&mut self) { + self.id = None; + } + + pub fn set_username(&mut self, username: String) { + self.username = Some(username); + } + + pub fn with_username(mut self, username: String) -> User { + self.username = Some(username); + self + } + + pub fn username(&self) -> Option<&String> { + self.username.as_ref() + } + + pub fn reset_username(&mut self) { + self.username = None; + } + + pub fn set_first_name(&mut self, first_name: String) { + self.first_name = Some(first_name); + } + + pub fn with_first_name(mut self, first_name: String) -> User { + self.first_name = Some(first_name); + self + } + + pub fn first_name(&self) -> Option<&String> { + self.first_name.as_ref() + } + + pub fn reset_first_name(&mut self) { + self.first_name = None; + } + + pub fn set_last_name(&mut self, last_name: String) { + self.last_name = Some(last_name); + } + + pub fn with_last_name(mut self, last_name: String) -> User { + self.last_name = Some(last_name); + self + } + + pub fn last_name(&self) -> Option<&String> { + self.last_name.as_ref() + } + + pub fn reset_last_name(&mut self) { + self.last_name = None; + } + + pub fn set_email(&mut self, email: String) { + self.email = Some(email); + } + + pub fn with_email(mut self, email: String) -> User { + self.email = Some(email); + self + } + + pub fn email(&self) -> Option<&String> { + self.email.as_ref() + } + + pub fn reset_email(&mut self) { + self.email = None; + } + + pub fn set_password(&mut self, password: String) { + self.password = Some(password); + } + + pub fn with_password(mut self, password: String) -> User { + self.password = Some(password); + self + } + + pub fn password(&self) -> Option<&String> { + self.password.as_ref() + } + + pub fn reset_password(&mut self) { + self.password = None; + } + + pub fn set_phone(&mut self, phone: String) { + self.phone = Some(phone); + } + + pub fn with_phone(mut self, phone: String) -> User { + self.phone = Some(phone); + self + } + + pub fn phone(&self) -> Option<&String> { + self.phone.as_ref() + } + + pub fn reset_phone(&mut self) { + self.phone = None; + } + + pub fn set_user_status(&mut self, user_status: i32) { + self.user_status = Some(user_status); + } + + pub fn with_user_status(mut self, user_status: i32) -> User { + self.user_status = Some(user_status); + self + } + + pub fn user_status(&self) -> Option<&i32> { + self.user_status.as_ref() + } + + pub fn reset_user_status(&mut self) { + self.user_status = None; + } + +} + + + diff --git a/samples/client/petstore/rust/.openapi-generator/VERSION b/samples/client/petstore/rust/.openapi-generator/VERSION index a0cd9f0ccb0..a6527129083 100644 --- a/samples/client/petstore/rust/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/.openapi-generator/VERSION @@ -1 +1 @@ -3.1.0 \ No newline at end of file +3.3.2-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/Cargo.toml b/samples/client/petstore/rust/Cargo.toml index 29cb240bc50..2ccdd989058 100644 --- a/samples/client/petstore/rust/Cargo.toml +++ b/samples/client/petstore/rust/Cargo.toml @@ -4,14 +4,14 @@ version = "1.0.0" authors = ["OpenAPI Generator team and contributors"] [dependencies] -serde = "1.0" -serde_derive = "1.0" -serde_yaml = "0.7" -serde_json = "1.0" -base64 = "~0.7.0" -futures = "0.1.16" -hyper = "0.11.6" +serde = "^1.0" +serde_derive = "^1.0" +serde_json = "^1.0" url = "1.5" +hyper = "~0.11" +serde_yaml = "0.7" +base64 = "~0.7.0" +futures = "0.1.23" [dev-dependencies] tokio-core = "*" diff --git a/samples/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 716a3c04d0a..333648af894 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -86,7 +86,7 @@ Multiple status values can be provided with comma separated strings Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **status** | [**Vec<String>**](String.md)| Status values that need to be considered for filter | + **status** | [**Vec**](String.md)| Status values that need to be considered for filter | ### Return type @@ -114,7 +114,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **tags** | [**Vec<String>**](String.md)| Tags to filter by | + **tags** | [**Vec**](String.md)| Tags to filter by | ### Return type diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index 91f2368dfb6..ea16bc1218e 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -49,7 +49,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**Vec<::models::User>**](array.md)| List of user object | + **user** | [**Vec<::models::User>**](array.md)| List of user object | ### Return type @@ -74,7 +74,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**Vec<::models::User>**](array.md)| List of user object | + **user** | [**Vec<::models::User>**](array.md)| List of user object | ### Return type diff --git a/samples/client/petstore/rust/pom.xml b/samples/client/petstore/rust/pom.xml index 1b803f27b0e..86adf2289ec 100644 --- a/samples/client/petstore/rust/pom.xml +++ b/samples/client/petstore/rust/pom.xml @@ -35,8 +35,7 @@ cargo - build - --release + check diff --git a/samples/client/petstore/rust/src/lib.rs b/samples/client/petstore/rust/src/lib.rs index b51fea8150e..a76d822525d 100644 --- a/samples/client/petstore/rust/src/lib.rs +++ b/samples/client/petstore/rust/src/lib.rs @@ -1,11 +1,11 @@ #[macro_use] extern crate serde_derive; -extern crate hyper; extern crate serde; extern crate serde_json; -extern crate futures; extern crate url; +extern crate hyper; +extern crate futures; pub mod apis; pub mod models;