Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[rust] Added support for text/plain to reqwest clients #20643

Merged
merged 8 commits into from
Feb 17, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,24 @@ public boolean isRestful() {
return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy();
}

/**
* Check if operation produces text/plain responses.
* NOTE: This does not mean it _only_ produces text/plain, just that it is one of the produces types.
*
* @return true if at least one produces is text/plain
*/
public boolean producesTextPlain() {
if (produces != null) {
for (Map<String, String> produce : produces) {
if ("text/plain".equalsIgnoreCase(produce.get("mediaType").split(";")[0].trim())
&& "String".equals(returnType)) {
return true;
}
}
}
return false;
}

/**
* Get the substring except baseName from path
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -817,17 +817,10 @@ public int compare(CodegenParameter one, CodegenParameter another) {
if (NATIVE.equals(getLibrary()) || APACHE.equals(getLibrary())) {
OperationMap operations = objs.getOperations();
List<CodegenOperation> operationList = operations.getOperation();
Pattern methodPattern = Pattern.compile("^(.*):([^:]*)$");
for (CodegenOperation op : operationList) {
// add extension to indicate content type is `text/plain` and the response type is `String`
if (op.produces != null) {
for (Map<String, String> produce : op.produces) {
if ("text/plain".equalsIgnoreCase(produce.get("mediaType").split(";")[0].trim())
&& "String".equals(op.returnType)) {
op.vendorExtensions.put("x-java-text-plain-string", true);
continue;
}
}
if ("String".equals(op.returnType) && op.producesTextPlain()) {
op.vendorExtensions.put("x-java-text-plain-string", true);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,10 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
operation.vendorExtensions.put("x-group-parameters", Boolean.TRUE);
}

if (operation.producesTextPlain() && "String".equals(operation.returnType)) {
operation.vendorExtensions.put("x-supports-plain-text", Boolean.TRUE);
}

// update return type to conform to rust standard
/*
if (operation.returnType != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use mockall::automock;
{{/mockall}}
use reqwest;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration};
use crate::apis::ContentType;

{{#mockall}}
#[cfg_attr(feature = "mockall", automock)]
Expand Down Expand Up @@ -336,6 +337,16 @@ impl {{classname}} for {{classname}}Client {
let local_var_resp = local_var_client.execute(local_var_req).await?;

let local_var_status = local_var_resp.status();
{{^supportMultipleResponses}}
{{#returnType}}
let local_var_content_type = local_var_resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let local_var_content_type = super::ContentType::from(local_var_content_type);
{{/returnType}}
{{/supportMultipleResponses}}
let local_var_content = local_var_resp.text().await?;

if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
Expand All @@ -344,7 +355,16 @@ impl {{classname}} for {{classname}}Client {
Ok(())
{{/returnType}}
{{#returnType}}
serde_json::from_str(&local_var_content).map_err(Error::from)
match local_var_content_type {
ContentType::Json => serde_json::from_str(&local_var_content).map_err(Error::from),
{{#vendorExtensions.x-supports-plain-text}}
ContentType::Text => return Ok(local_var_content),
{{/vendorExtensions.x-supports-plain-text}}
{{^vendorExtensions.x-supports-plain-text}}
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))),
{{/vendorExtensions.x-supports-plain-text}}
ContentType::Unsupported(local_var_unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{local_var_unknown_type}` content type response that cannot be converted to `{{returnType}}`")))),
}
{{/returnType}}
{{/supportMultipleResponses}}
{{#supportMultipleResponses}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,27 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String
unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}

impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
return Self::Json;
} else if content_type.starts_with("text/plain") {
return Self::Text;
} else {
return Self::Unsupported(content_type.to_string());
}
}
}

{{#apiInfo}}
{{#apis}}
pub mod {{{classFilename}}};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{{>partial_header}}

use reqwest;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration};
use super::{Error, configuration, ContentType};

{{#operations}}
{{#operation}}
Expand Down Expand Up @@ -355,6 +355,18 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration:
let resp = configuration.client.execute(req){{#supportAsync}}.await{{/supportAsync}}?;

let status = resp.status();
{{^supportMultipleResponses}}
{{^isResponseFile}}
{{#returnType}}
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
{{/returnType}}
{{/isResponseFile}}
{{/supportMultipleResponses}}

if !status.is_client_error() && !status.is_server_error() {
{{^supportMultipleResponses}}
Expand All @@ -367,7 +379,16 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration:
{{/returnType}}
{{#returnType}}
let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?;
serde_json::from_str(&content).map_err(Error::from)
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
{{#vendorExtensions.x-supports-plain-text}}
ContentType::Text => return Ok(content),
{{/vendorExtensions.x-supports-plain-text}}
{{^vendorExtensions.x-supports-plain-text}}
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{returnType}}`"))),
{{/vendorExtensions.x-supports-plain-text}}
ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{returnType}}`")))),
}
{{/returnType}}
{{/isResponseFile}}
{{/supportMultipleResponses}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,27 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String
unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}

impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
return Self::Json;
} else if content_type.starts_with("text/plain") {
return Self::Text;
} else {
return Self::Unsupported(content_type.to_string());
}
Comment on lines +148 to +154
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rational for this logic is to be able to support both custom JSON variants and charset extensions.

  • application/json
  • application/vnd.github+json
  • application/json; charset=utf-8
  • application/vnd.github+json; charset=utf-8

as well as

  • text/plain
  • text/plain; charset=utf-8

}
}

{{#apiInfo}}
{{#apis}}
pub mod {{{classFilename}}};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,10 @@ paths:
application/json:
schema:
type: string
text/plain:
schema:
type: string

'400':
description: Invalid username/password supplied
/user/logout:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@


use reqwest;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration};
use super::{Error, configuration, ContentType};


/// struct for typed errors of method [`repro`]
Expand All @@ -36,10 +36,20 @@ pub fn repro(configuration: &configuration::Configuration, ) -> Result<models::P
let resp = configuration.client.execute(req)?;

let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);

if !status.is_client_error() && !status.is_server_error() {
let content = resp.text()?;
serde_json::from_str(&content).map_err(Error::from)
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Parent`"))),
ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Parent`")))),
}
} else {
let content = resp.text()?;
let entity: Option<ReproError> = serde_json::from_str(&content).ok();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,27 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String
unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}

impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
return Self::Json;
} else if content_type.starts_with("text/plain") {
return Self::Text;
} else {
return Self::Unsupported(content_type.to_string());
}
}
}

pub mod default_api;

pub mod configuration;
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@


use reqwest;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration};
use super::{Error, configuration, ContentType};


/// struct for typed errors of method [`demo_color_get`]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,27 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String
unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}

impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
return Self::Json;
} else if content_type.starts_with("text/plain") {
return Self::Text;
} else {
return Self::Unsupported(content_type.to_string());
}
}
}

pub mod default_api;

pub mod configuration;
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@


use reqwest;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration};
use super::{Error, configuration, ContentType};


/// struct for typed errors of method [`create_state`]
Expand Down Expand Up @@ -69,10 +69,20 @@ pub fn get_state(configuration: &configuration::Configuration, ) -> Result<model
let resp = configuration.client.execute(req)?;

let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);

if !status.is_client_error() && !status.is_server_error() {
let content = resp.text()?;
serde_json::from_str(&content).map_err(Error::from)
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetState200Response`"))),
ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetState200Response`")))),
}
} else {
let content = resp.text()?;
let entity: Option<GetStateError> = serde_json::from_str(&content).ok();
Expand Down
21 changes: 21 additions & 0 deletions samples/client/others/rust/reqwest/composed-oneof/src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,27 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String
unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
Json,
Text,
Unsupported(String)
}

impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
if content_type.starts_with("application") && content_type.contains("json") {
return Self::Json;
} else if content_type.starts_with("text/plain") {
return Self::Text;
} else {
return Self::Unsupported(content_type.to_string());
}
}
}

pub mod default_api;

pub mod configuration;
Loading
Loading