openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

rust: better support for binary body parameters

Open jclulow opened this issue 3 years ago • 5 comments

The Rust-based reqwest client does not correctly handle a binary body parameter today. It creates a PathBuf parameter and attempts to pass that to the RequestBuilder json() method, which sends the path itself as the body of the request.

Instead, it would help to parameterise operations that accept a binary body so that they may accept any object that implements the Into<Body> trait. This would allow the caller to pass a binary body in several forms, such as a slice of bytes or a Stream that reads from some other source.

Note possible related issue: #5218

PR checklist

  • [x] Read the contribution guidelines.
  • [x] Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • [x] Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh
    ./bin/utils/export_docs_generators.sh
    
    Commit all changed files. This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*. For Windows users, please run the script in Git BASH.
  • [x] File the PR against the correct branch: master, 5.1.x, 6.0.x
  • [x] If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request. (cc @ahl @frol @farcaller @richardwhiuk @paladinzh)

jclulow avatar Mar 19 '21 21:03 jclulow

While the sample application does not currently have any binary body parameters, I have one in another application I am working on. This portion of the API definition document:

    "/v1/worker/task/{task}/chunk": {
      "post": {
        "operationId": "worker_task_upload_chunk",
        "parameters": [
          {
            "in": "path",
            "name": "task",
            "required": true,
            "schema": {
              "type": "string"
            },
            "style": "simple"
          }
        ],
        "requestBody": {
          "content": {
            "application/octet-stream": {
              "schema": {
                "type": "string",
                "format": "binary"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "successful creation",
            "content": {
              "application/json": {
                "schema": {
                  "title": "UploadedChunk",
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    }
                  },
                  "required": [
                    "id"
                  ]
                }
              }
            }
          }
        }
      }
    },

... becomes the following generated routine ...

pub async fn worker_task_upload_chunk<B: Into<reqwest::Body>>(
    configuration: &configuration::Configuration,
    task: &str,
    body: B,
) -> Result<crate::models::UploadedChunk, Error<WorkerTaskUploadChunkError>> {

    let local_var_client = &configuration.client;

    let local_var_uri_str = format!("{}/v1/worker/task/{task}/chunk", configuration.base_path, task=crate::apis::urlencode(task));
    let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());

    if let Some(ref local_var_user_agent) = configuration.user_agent {
        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
    }
    local_var_req_builder = local_var_req_builder.body(body);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_content = local_var_resp.text().await?;

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        serde_json::from_str(&local_var_content).map_err(Error::from)
    } else {
        let local_var_entity: Option<WorkerTaskUploadChunkError> = serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
        Err(Error::ResponseError(local_var_error))
    }
}

jclulow avatar Mar 19 '21 21:03 jclulow

Thanks Joshua for your work on implementing a more generic approach to uploading bytes, this specific feature is quite useful for a project we are building at www.smartlayers.io

dkatz23238 avatar Sep 13 '21 22:09 dkatz23238

@bcourtine this seems relevant to the TODO you put in https://github.com/OpenAPITools/openapi-generator/pull/1890

jayvdb avatar Oct 17 '22 07:10 jayvdb

I believe that this PR should enhance https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml to include an endpoint which triggers this new code, and then the samples will generate the new code.

jayvdb avatar Oct 31 '22 07:10 jayvdb

What's the status here? I need a Vec<u8> in the body and PathBuf isn't very helpful.

aDogCalledSpot avatar May 13 '24 15:05 aDogCalledSpot