Skip to content

toCurl drops multipart filename, content-type, and per-part headers #2881

@haskiindahouse

Description

@haskiindahouse

request.toCurl is great for sharing a request to debug, but for multipart bodies it silently throws away Part.fileName, Part.contentType, and Part.headers. The resulting curl command sends a different request than the original.

Reproducer (scala-cli):

//> using scala 3.8.3
//> using dep com.softwaremill.sttp.client4::core::4.0.5

import sttp.client4.*
import sttp.model.*

@main def run(): Unit =
  val request = basicRequest
    .post(uri"http://example.com/upload")
    .multipartBody(
      multipart("file", "file content")
        .fileName("document.pdf")
        .contentType("application/pdf"),
      multipart("field", "value")
    )
  println(request.toCurl)

Output:

curl \
  --request POST \
  --url 'http://example.com/upload' \
  --form 'file=file content' \
  --form 'field=value' \
  --location \
  --max-redirs 32

Expected something like --form 'file=file content;filename=document.pdf;type=application/pdf'.

Source:

def handleMultipartBody(parts: Seq[Part[GenericRequestBody[_]]]): String =
parts
.map { p =>
p.body match {
case StringBody(s, _, _) => s"--form '${p.name}=$s'"
case FileBody(f, _) => s"--form '${p.name}=@${f.name}'"
case _ => s"--data-binary <PLACEHOLDER>"
}
}
.mkString(newline)

def handleMultipartBody(parts: Seq[Part[GenericRequestBody[_]]]): String =
  parts.map { p =>
    p.body match {
      case StringBody(s, _, _) => s"--form '${p.name}=$s'"
      case FileBody(f, _)      => s"--form '${p.name}=@${f.name}'"
      case _                   => s"--data-binary <PLACEHOLDER>"
    }
  }.mkString(newline)

p.fileName, p.contentType, and p.headers aren't read at all, and any non-StringBody/FileBody part collapses to a literal placeholder. curl supports the metadata via the ;filename=...;type=... and ;headers=@... extensions, so a faithful renderer is feasible.

A sketch (StringBody case):

case StringBody(s, _, _) =>
  val tail = (p.fileName.map(fn => s";filename=$fn").toList ++
              p.contentType.map(ct => s";type=$ct").toList).mkString
  s"--form '${p.name}=$s$tail'"

Happy to PR with full coverage of the four part-body shapes plus a unit test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions