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 7 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 @@ -677,6 +677,10 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
operation.vendorExtensions.put("x-group-parameters", Boolean.TRUE);
}

if ("String".equals(operation.returnType)) {
operation.vendorExtensions.put("x-supports-plain-text", Boolean.TRUE);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I would not call this a vendor extension since its not meant for the API spec to set x-supports-plain-text.
I just needed a way to set attach some arbitrary metadata to an operation and this was the easiest way that I found to do it.

If there is a better way to do this, please let me know.

Copy link
Member

Choose a reason for hiding this comment

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

in java client codegen, we've something similar:

if ("text/plain".equalsIgnoreCase(produce.get("mediaType").split(";")[0].trim())

Copy link
Member

Choose a reason for hiding this comment

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

if i remember correctly, there was a use case before which the content type is application/json and the return type is string (e.g. "something here") so I think we will need to check the content type (produce) as well

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure that makes sense. I extracted the logic that the JavaClientCodegen into a re-useable function in CodegenOperation in 149eaa4


// 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 @@ -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;
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 [`endpoint_get`]
Expand All @@ -36,10 +36,20 @@ pub fn endpoint_get(configuration: &configuration::Configuration, ) -> Result<mo
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::EmptyObject`"))),
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::EmptyObject`")))),
}
} else {
let content = resp.text()?;
let entity: Option<EndpointGetError> = serde_json::from_str(&content).ok();
Expand Down
21 changes: 21 additions & 0 deletions samples/client/others/rust/reqwest/emptyObject/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