Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/rust-petstore.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ for spec_path in \
; do
spec=$(basename "$spec_path" | sed 's/.yaml//' | sed 's/.json//' )

for library in hyper reqwest; do
for library in hyper reqwest reqwestFutures; do
args="generate --template-dir modules/openapi-generator/src/main/resources/rust
--input-spec $spec_path
--generator-name rust
Expand Down
10 changes: 10 additions & 0 deletions bin/windows/rust-futures-petstore.bat
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar

If Not Exist %executable% (
mvn clean package
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g rust --library reqwestFutures -o samples\client\petstore\rust

java %JAVA_OPTS% -jar %executable% %ags%
3 changes: 2 additions & 1 deletion docs/generators/rust.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,5 +7,6 @@ sidebar_label: rust
| ------ | ----------- | ------ | ------- |
|packageName|Rust package name (convention: lowercase).| |openapi|
|packageVersion|Rust package version.| |1.0.0|
|interfacePrefix|Method prefix.| ||
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dl>|hyper|
|library|library template (sub-template) to use.|<dl><dt>**hyper**</dt><dd>HTTP client: Hyper.</dd><dt>**reqwest**</dt><dd>HTTP client: Reqwest.</dd><dt>**reqwestFutures**</dt><dd>HTTP client: Reqwest (futures).</dd><dl>|hyper|
Original file line numberDiff line numberDiff line change
Expand Up@@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {

public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
public static final String REQWEST_FUTURES_LIBRARY = "reqwestFutures";

protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
Expand DownExpand Up@@ -136,11 +137,14 @@ public RustClientCodegen() {
.defaultValue("openapi"));
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.")
.defaultValue("1.0.0"));
cliOptions.add(new CliOption(CodegenConstants.INTERFACE_PREFIX, "Method prefix.")
.defaultValue(""));
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.");
supportedLibraries.put(REQWEST_FUTURES_LIBRARY, "HTTP client: Reqwest (futures).");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
Expand DownExpand Up@@ -221,6 +225,8 @@ public void processOpts() {
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else if (REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
additionalProperties.put("reqwestFutures", "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
Expand DownExpand Up@@ -431,7 +437,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
// 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())) {
} else if (REQWEST_LIBRARY.equals(getLibrary()) || REQWEST_FUTURES_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,11 @@ futures = "0.1.23"
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
{{#reqwestFutures}}
reqwest = "~0.9"
futures = "0.1.23"
mime_guess = "2.0.1"
{{/reqwestFutures}}

[dev-dependencies]
{{#hyper}}
Expand Down
231 changes: 231 additions & 0 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
#[allow(unused_imports)]
use std::option::Option;

use reqwest;

use super::{Error, configuration};

pub struct {{{classname}}}Client {
configuration: Rc<configuration::Configuration>,
}

impl {{{classname}}}Client {
pub fn new(configuration: Rc<configuration::Configuration>) -> {{{classname}}}Client {
{{{classname}}}Client {
configuration,
}
}
}

pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>;
{{/operation}}
{{/operations}}
}

impl {{{classname}}} for {{{classname}}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error> {
let configuration: &configuration::Configuration = self.configuration.borrow();
let client = &configuration.client;

let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}});
let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str());

{{#queryParams}}
{{#required}}
req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
{{/required}}
{{^required}}
if let Some(ref s) = {{{paramName}}} {
req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(","){{/isListContainer}}.to_string())]);
}
{{/required}}
{{/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,
};
req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]);
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
{{#hasHeaderParams}}
{{#headerParams}}
{{#required}}
{{^isNullable}}
req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { req_builder = req_builder.header("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/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}}
{{^isBasicBearer}}
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());
};
{{/isBasicBearer}}
{{#isBasicBearer}}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#isMultipart}}
{{#hasFormParams}}
let mut form = reqwest::multipart::Form::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form = form.file("{{{baseName}}}", {{{paramName}}})?;
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; },
None => { unimplemented!("Required nullable form file param not supported"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.file("{{{baseName}}}", param_value)?;
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form = form.text("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.multipart(form);
{{/hasFormParams}}
{{/isMultipart}}
{{^isMultipart}}
{{#hasFormParams}}
let mut form_params = std::collections::HashMap::new();
{{#formParams}}
{{#isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); },
None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content"));
}
{{/required}}
{{/isFile}}
{{^isFile}}
{{#required}}
{{^isNullable}}
form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/isNullable}}
{{#isNullable}}
match {{{paramName}}} {
Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); },
None => { form_params.insert("{{{baseName}}}", ""); },
}
{{/isNullable}}
{{/required}}
{{^required}}
if let Some(param_value) = {{{paramName}}} {
form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
}
{{/required}}
{{/isFile}}
{{/formParams}}
req_builder = req_builder.form(&form_params);
{{/hasFormParams}}
{{/isMultipart}}
{{#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}}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,6 +11,11 @@ extern crate futures;
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
{{#reqwestFutures}}
extern crate reqwest;
extern crate futures;
extern crate mime_guess;
{{/reqwestFutures}}

pub mod apis;
pub mod models;
Loading