diff --git a/bin/configs/rust-reqwest-nullable-enum-query-params.yaml b/bin/configs/rust-reqwest-nullable-enum-query-params.yaml new file mode 100644 index 000000000000..9dcee7df4ad9 --- /dev/null +++ b/bin/configs/rust-reqwest-nullable-enum-query-params.yaml @@ -0,0 +1,8 @@ +generatorName: rust +outputDir: samples/client/others/rust/reqwest/nullable-enum-query-params +library: reqwest +inputSpec: modules/openapi-generator/src/test/resources/3_1/rust/nullable-enum-query-params.yaml +templateDir: modules/openapi-generator/src/main/resources/rust +additionalProperties: + supportAsync: true + packageName: nullable-enum-query-params-reqwest diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index 7f42d081ed00..3c70fb2b73b2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -774,19 +774,18 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List operations = objectMap.getOperation(); for (CodegenOperation operation : operations) { - if (operation.pathParams != null && operation.pathParams.size() > 0) { - - // For types with `isAnyType` we assume it's a `serde_json::Value` type. - // However for path, query, and headers it's unlikely to be JSON so we default to `String`. - // Note that we keep the default `serde_json::Value` for body parameters. - for (var param : operation.allParams) { - if (param.isAnyType && (param.isPathParam || param.isQueryParam || param.isHeaderParam)) { - param.dataType = "String"; - param.isPrimitiveType = true; - param.isString = true; - } + // For types with `isAnyType` we assume it's a `serde_json::Value` type. + // However for path, query, and headers it's unlikely to be JSON so we default to `String`. + // Note that we keep the default `serde_json::Value` for body parameters. + for (var param : operation.allParams) { + if (param.isAnyType && (param.isPathParam || param.isQueryParam || param.isHeaderParam)) { + param.dataType = "String"; + param.isPrimitiveType = true; + param.isString = true; } + } + if (operation.pathParams != null && operation.pathParams.size() > 0) { for (var pathParam : operation.pathParams) { if (!pathParam.baseName.contains("-")) { continue; diff --git a/modules/openapi-generator/src/test/resources/3_1/rust/nullable-enum-query-params.yaml b/modules/openapi-generator/src/test/resources/3_1/rust/nullable-enum-query-params.yaml new file mode 100644 index 000000000000..57ac7d4d75e5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/rust/nullable-enum-query-params.yaml @@ -0,0 +1,88 @@ +openapi: 3.1.0 +info: + title: Nullable Enum Query Parameter Test + description: >- + Test spec for enum query parameters whose schema is not a bare $ref, as + emitted by FastAPI and other 3.1 producers. The same operation is defined + with and without a path parameter, because the two used to be generated + differently. + version: 1.0.0 +paths: + /widgets/summary: + get: + operationId: getWidgetSummary + summary: Get a widget summary + parameters: + - name: kind + in: query + description: Kind filter, expressed as an anyOf with null + required: false + schema: + anyOf: + - $ref: '#/components/schemas/WidgetKind' + - type: 'null' + title: Kind + - name: sort + in: query + description: Sort order, expressed as a $ref with sibling keywords + required: false + schema: + $ref: '#/components/schemas/SortDirection' + title: Sort + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetSummary' + /widgets/{widget_id}/summary: + get: + operationId: getWidgetSummaryById + summary: Get a widget summary for a single widget + parameters: + - name: widget_id + in: path + required: true + schema: + type: string + - name: kind + in: query + description: Kind filter, expressed as an anyOf with null + required: false + schema: + anyOf: + - $ref: '#/components/schemas/WidgetKind' + - type: 'null' + title: Kind + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetSummary' +components: + schemas: + WidgetKind: + type: string + description: Widget kind + enum: + - basic + - premium + SortDirection: + type: string + description: Sort direction options + enum: + - asc + - desc + WidgetSummary: + type: object + properties: + kind: + $ref: '#/components/schemas/WidgetKind' + total: + type: integer + required: + - kind + - total diff --git a/samples/client/others/rust/Cargo.lock b/samples/client/others/rust/Cargo.lock index 4e2285a69629..04b5af7b9803 100644 --- a/samples/client/others/rust/Cargo.lock +++ b/samples/client/others/rust/Cargo.lock @@ -867,6 +867,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "nullable-enum-query-params-reqwest" +version = "1.0.0" +dependencies = [ + "reqwest 0.13.1", + "serde", + "serde_json", + "serde_repr", + "url", +] + [[package]] name = "num_cpus" version = "1.17.0" diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/.gitignore b/samples/client/others/rust/reqwest/nullable-enum-query-params/.gitignore new file mode 100644 index 000000000000..6aa106405a4b --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator-ignore b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/FILES b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/FILES new file mode 100644 index 000000000000..72cd90e9aedf --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/FILES @@ -0,0 +1,18 @@ +.gitignore +.openapi-generator-ignore +.travis.yml +Cargo.toml +README.md +docs/DefaultApi.md +docs/SortDirection.md +docs/WidgetKind.md +docs/WidgetSummary.md +git_push.sh +src/apis/configuration.rs +src/apis/default_api.rs +src/apis/mod.rs +src/lib.rs +src/models/mod.rs +src/models/sort_direction.rs +src/models/widget_kind.rs +src/models/widget_summary.rs diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/VERSION b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/VERSION new file mode 100644 index 000000000000..8fc8df61083a --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.25.0-SNAPSHOT diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/.travis.yml b/samples/client/others/rust/reqwest/nullable-enum-query-params/.travis.yml new file mode 100644 index 000000000000..22761ba7ee19 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/Cargo.toml b/samples/client/others/rust/reqwest/nullable-enum-query-params/Cargo.toml new file mode 100644 index 000000000000..c49a8bce2e25 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "nullable-enum-query-params-reqwest" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently." +# Override this license by providing a License Object in the OpenAPI. +license = "Unlicense" +edition = "2021" + +[dependencies] +serde = { version = "^1.0", features = ["derive"] } +serde_json = "^1.0" +serde_repr = "^0.1" +url = "^2.5" +reqwest = { version = "^0.13", default-features = false, features = ["json", "multipart", "query", "form"] } + +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls = ["reqwest/rustls"] diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/README.md b/samples/client/others/rust/reqwest/nullable-enum-query-params/README.md new file mode 100644 index 000000000000..ac643b61d663 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/README.md @@ -0,0 +1,49 @@ +# Rust API client for nullable-enum-query-params-reqwest + +Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + + +## Overview + +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Generator version: 7.25.0-SNAPSHOT +- Build package: `org.openapitools.codegen.languages.RustClientCodegen` + +## Installation + +Put the package under your project folder in a directory named `nullable-enum-query-params-reqwest` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +nullable-enum-query-params-reqwest = { path = "./nullable-enum-query-params-reqwest" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**get_widget_summary**](docs/DefaultApi.md#get_widget_summary) | **GET** /widgets/summary | Get a widget summary +*DefaultApi* | [**get_widget_summary_by_id**](docs/DefaultApi.md#get_widget_summary_by_id) | **GET** /widgets/{widget_id}/summary | Get a widget summary for a single widget + + +## Documentation For Models + + - [SortDirection](docs/SortDirection.md) + - [WidgetKind](docs/WidgetKind.md) + - [WidgetSummary](docs/WidgetSummary.md) + + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + + + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/DefaultApi.md b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/DefaultApi.md new file mode 100644 index 000000000000..10e9f6bcb6da --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/DefaultApi.md @@ -0,0 +1,68 @@ +# \DefaultApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_widget_summary**](DefaultApi.md#get_widget_summary) | **GET** /widgets/summary | Get a widget summary +[**get_widget_summary_by_id**](DefaultApi.md#get_widget_summary_by_id) | **GET** /widgets/{widget_id}/summary | Get a widget summary for a single widget + + + +## get_widget_summary + +> models::WidgetSummary get_widget_summary(kind, sort) +Get a widget summary + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**kind** | Option<**String**> | Kind filter, expressed as an anyOf with null | | +**sort** | Option<**String**> | Sort order, expressed as a $ref with sibling keywords | | + +### Return type + +[**models::WidgetSummary**](WidgetSummary.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_widget_summary_by_id + +> models::WidgetSummary get_widget_summary_by_id(widget_id, kind) +Get a widget summary for a single widget + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**widget_id** | **String** | | [required] | +**kind** | Option<**String**> | Kind filter, expressed as an anyOf with null | | + +### Return type + +[**models::WidgetSummary**](WidgetSummary.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/SortDirection.md b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/SortDirection.md new file mode 100644 index 000000000000..a889d395b025 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/SortDirection.md @@ -0,0 +1,13 @@ +# SortDirection + +## Enum Variants + +| Name | Value | +|---- | -----| +| Asc | asc | +| Desc | desc | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetKind.md b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetKind.md new file mode 100644 index 000000000000..638d41981138 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetKind.md @@ -0,0 +1,13 @@ +# WidgetKind + +## Enum Variants + +| Name | Value | +|---- | -----| +| Basic | basic | +| Premium | premium | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetSummary.md b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetSummary.md new file mode 100644 index 000000000000..3ef8da8c5b86 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/docs/WidgetSummary.md @@ -0,0 +1,12 @@ +# WidgetSummary + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | [**models::WidgetKind**](WidgetKind.md) | | +**total** | **i32** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/git_push.sh b/samples/client/others/rust/reqwest/nullable-enum-query-params/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/configuration.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/configuration.rs new file mode 100644 index 000000000000..e940c244d748 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/configuration.rs @@ -0,0 +1,51 @@ +/* + * Nullable Enum Query Parameter Test + * + * Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: reqwest::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, +} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "http://localhost".to_owned(), + user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), + client: reqwest::Client::new(), + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + } + } +} diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/default_api.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/default_api.rs new file mode 100644 index 000000000000..e05366d129e8 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/default_api.rs @@ -0,0 +1,115 @@ +/* + * Nullable Enum Query Parameter Test + * + * Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + + +/// struct for typed errors of method [`get_widget_summary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetWidgetSummaryError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_widget_summary_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetWidgetSummaryByIdError { + UnknownValue(serde_json::Value), +} + + +pub async fn get_widget_summary(configuration: &configuration::Configuration, kind: Option<&str>, sort: Option<&str>) -> Result> { + // add a prefix to parameters to efficiently prevent name collisions + let p_query_kind = kind; + let p_query_sort = sort; + + let uri_str = format!("{}/widgets/summary", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref param_value) = p_query_kind { + req_builder = req_builder.query(&[("kind", ¶m_value.to_string())]); + } + if let Some(ref param_value) = p_query_sort { + req_builder = req_builder.query(&[("sort", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + 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().await?; + 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::WidgetSummary`"))), + 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::WidgetSummary`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn get_widget_summary_by_id(configuration: &configuration::Configuration, widget_id: &str, kind: Option<&str>) -> Result> { + // add a prefix to parameters to efficiently prevent name collisions + let p_path_widget_id = widget_id; + let p_query_kind = kind; + + let uri_str = format!("{}/widgets/{widget_id}/summary", configuration.base_path, widget_id=crate::apis::urlencode(p_path_widget_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref param_value) = p_query_kind { + req_builder = req_builder.query(&[("kind", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + 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().await?; + 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::WidgetSummary`"))), + 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::WidgetSummary`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/mod.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/mod.rs new file mode 100644 index 000000000000..fdcc89b36066 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/apis/mod.rs @@ -0,0 +1,116 @@ +use std::error; +use std::fmt; + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + }; + write!(f, "error in {}: {}", module, e) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => params.append(&mut parse_deep_object( + &format!("{}[{}]", prefix, key), + value, + )), + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{}[{}][{}]", prefix, key, i), + value, + )); + } + }, + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), + _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + } + + return params; + } + + 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; diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/lib.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/lib.rs new file mode 100644 index 000000000000..e1520628d762 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/lib.rs @@ -0,0 +1,11 @@ +#![allow(unused_imports)] +#![allow(clippy::too_many_arguments)] + +extern crate serde_repr; +extern crate serde; +extern crate serde_json; +extern crate url; +extern crate reqwest; + +pub mod apis; +pub mod models; diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/mod.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/mod.rs new file mode 100644 index 000000000000..eaccca2eacd5 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/mod.rs @@ -0,0 +1,6 @@ +pub mod sort_direction; +pub use self::sort_direction::SortDirection; +pub mod widget_kind; +pub use self::widget_kind::WidgetKind; +pub mod widget_summary; +pub use self::widget_summary::WidgetSummary; diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/sort_direction.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/sort_direction.rs new file mode 100644 index 000000000000..912c1ca38ea4 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/sort_direction.rs @@ -0,0 +1,39 @@ +/* + * Nullable Enum Query Parameter Test + * + * Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// SortDirection : Sort direction options +/// Sort direction options +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum SortDirection { + #[serde(rename = "asc")] + Asc, + #[serde(rename = "desc")] + Desc, + +} + +impl std::fmt::Display for SortDirection { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Asc => write!(f, "asc"), + Self::Desc => write!(f, "desc"), + } + } +} + +impl Default for SortDirection { + fn default() -> SortDirection { + Self::Asc + } +} + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_kind.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_kind.rs new file mode 100644 index 000000000000..e43b5041cd95 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_kind.rs @@ -0,0 +1,39 @@ +/* + * Nullable Enum Query Parameter Test + * + * Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// WidgetKind : Widget kind +/// Widget kind +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum WidgetKind { + #[serde(rename = "basic")] + Basic, + #[serde(rename = "premium")] + Premium, + +} + +impl std::fmt::Display for WidgetKind { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Basic => write!(f, "basic"), + Self::Premium => write!(f, "premium"), + } + } +} + +impl Default for WidgetKind { + fn default() -> WidgetKind { + Self::Basic + } +} + diff --git a/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_summary.rs b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_summary.rs new file mode 100644 index 000000000000..fbd1f7cfa291 --- /dev/null +++ b/samples/client/others/rust/reqwest/nullable-enum-query-params/src/models/widget_summary.rs @@ -0,0 +1,30 @@ +/* + * Nullable Enum Query Parameter Test + * + * Test spec for enum query parameters whose schema is not a bare $ref, as emitted by FastAPI and other 3.1 producers. The same operation is defined with and without a path parameter, because the two used to be generated differently. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct WidgetSummary { + #[serde(rename = "kind")] + pub kind: models::WidgetKind, + #[serde(rename = "total")] + pub total: i32, +} + +impl WidgetSummary { + pub fn new(kind: models::WidgetKind, total: i32) -> WidgetSummary { + WidgetSummary { + kind, + total, + } + } +} +