• Swift 6
  • Apple platforms + Linux
  • No dependencies

URLRequest in,
safe curl out.

swift-curl turns any Foundation request into a curl command you can paste into bash, zsh, sh or ksh, and curl receives exactly the request you built. Quotes, $, backticks, newlines and binary bytes included. Nothing is ever expanded.

Request.swift
import SwiftCURL

var request = URLRequest(url: URL(string: "https://api.example.com/users")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = Data(#"{"name":"O'Brien"}"#.utf8)

print(try request.curl(format: .multiline))
Output
curl 'https://api.example.com/users' \
  -H 'Content-Type: application/json' \
  --data-raw '{"name":"O'\''Brien"}'

The problem

“Copy as cURL” is string interpolation into a shell.

Every app that logs requests as curl ends up writing the same few lines, and they work until a value contains an apostrophe, a $ or a newline. Then the command breaks, or worse, the shell runs part of it.

Hand-rolled
let header = "-H \"\(name): \(value)\""
let body = "-d '\(text)'"
  • Double quotes expand $HOME, $(…) and backticks from header values.
  • An apostrophe in a JSON body closes the single quote and leaves the rest to the shell.
  • -d @file makes curl read a local file; -X HEAD hangs waiting for a body.
  • NUL and other binary bytes cannot travel in an argument at all.
swift-curl
var request = URLRequest(url: URL(string: "https://example.com/search?q=$(whoami)")!)
request.setValue("`rm -rf ~`; echo $HOME", forHTTPHeaderField: "X-Note")
print(try request.curl())
// curl 'https://example.com/search?q=$(whoami)' -H 'X-Note: `rm -rf ~`; echo $HOME'
  • Every value is single-quoted, where no POSIX shell expands anything; ' becomes '\''.
  • Text bodies use --data-raw, so a leading @ is never a file name.
  • Binary bodies are piped through base64 --decode, byte-exact.
  • Methods and header names outside the RFC 9110 token set, and CR/LF in values, throw instead of rendering.

What you get

A typed command, not a string.

Conversion produces a CURLCommand: inspect it, append options, read the exact argv curl will receive, then render it the way you want.

Injection-safe by construction

One quoting function, single quotes only. The only $ ever emitted is a variable you asked for. Architecture rules keep it that way.

Secrets stay out

ShellSubstitution writes a token as "$API_TOKEN", even when it appears base64 or percent-encoded. Share the command, not the credential.

Logging that never throws

request.curlDescription redacts Authorization, cookies and API keys, omits binary and streamed bodies, and degrades to an inert shell comment.

Byte-exact bodies

UTF-8 text goes in --data-raw; anything with NUL or control bytes is piped through base64. Multipart can stay raw or become --form-string / -F fields.

curl's quirks handled

-I for HEAD, no redundant -X, -g for URLs with brackets, --url for URLs starting with -, Name; for empty header values.

Swift 6, everywhere

Sendable, Hashable and Codable models, typed throws, Foundation only. macOS, iOS, tvOS, watchOS, visionOS and Linux.

Examples

Real output, from the current release.

Keep a token out of the command

Every occurrence of the literal, in the URL or any option value, becomes a double-quoted variable reference. The literal parts stay single-quoted, and the command runs once the variable is set.

var request = URLRequest(url: URL(string: "https://api.example.com/users?key=s3cr3t")!)
request.setValue("Bearer s3cr3t", forHTTPHeaderField: "Authorization")

let token = ShellSubstitution(literal: "s3cr3t", variable: "API_TOKEN")!
print(try request.curlCommand().render(.init(layout: .multiline(indentation: "  "), substitutions: [token])))
curl 'https://api.example.com/users?key='"$API_TOKEN" \
  -H 'Authorization: Bearer '"$API_TOKEN"

Encoded spellings too

HTTP Basic carries the credentials base64-encoded. Give the encoded text and its encoding: the command computes it from the plain value with POSIX tools, so curl receives the same bytes.

let basic = Data("alice:s3cr3t".utf8).base64EncodedString()
request.setValue("Basic " + basic, forHTTPHeaderField: "Authorization")
let credentials = ShellSubstitution(literal: basic, variable: "CREDENTIALS", encoding: .base64)!
print(try request.curlCommand().render(.init(substitutions: [credentials])))
curl 'https://api.example.com/me' -H 'Authorization: Basic '"$(printf %s "$CREDENTIALS" | base64 | tr -d '\n')"

Log every request, safely

A never-throwing description built from the .logging preset: credentials redacted, binary and streamed bodies omitted.

request.setValue("Bearer eyJhbGciOi.secret", forHTTPHeaderField: "Authorization")
request.setValue("session=abc123", forHTTPHeaderField: "Cookie")
logger.debug("\(request.curlDescription)")
// curl 'https://api.example.com/me' -H 'Authorization: REDACTED' -H 'Cookie: REDACTED'

Binary bodies, byte for byte

A NUL byte can never be part of a shell argument, so binary data is piped into curl's standard input.

request.httpMethod = "PUT"
request.setValue("image/png", forHTTPHeaderField: "Content-Type")
request.httpBody = Data([0x89, 0x50, 0x4E, 0x47, 0x00, 0x0D, 0x0A, 0x1A])
print(try request.curl(format: .multiline))
printf '%s' 'iVBORwANCho=' \
  | base64 --decode \
  | curl 'https://api.example.com/upload' \
  -X 'PUT' \
  -H 'Content-Type: image/png' \
  --data-binary '@-'

Work with the model

Options for conversion, options for rendering, and the exact argv curl will see after the shell removes the quoting.

var command = try request.curlCommand(options: .init {
  $0.followRedirects = true
  $0.compressed = true
})
command.options.append(.verbose)

command.arguments()
// ["https://api.example.com/users", "-X", "DELETE", "-L", "--compressed", "-v"]
command.render(.init(layout: .multiline(indentation: "  "), flagStyle: .long))
// curl 'https://api.example.com/users' \
//   --request 'DELETE' \
//   --location \
//   --compressed \
//   --verbose

Proof, not promises

Run in real shells. Measured. Checked.

  • Real shells. The test suite replaces curl with a function that dumps its argv and standard input, then runs every generated command in bash, sh/dash, zsh and ksh. Hostile and fuzzed input ($(), backticks, !!, quotes, newlines, Unicode) must arrive intact.
  • Architecture rules. swift-llm-check tests fail the build if any code but ShellEscaping writes quoting, if a $ appears outside ShellSubstitution, or if a value is ever left unquoted. All rules.
  • Benchmarks. Conversion and rendering are measured with package-benchmark: wall clock, CPU, mallocs, peak memory. Method and results.
Release build, p500.3.00.3.1
Render a 1 MB JSON body172 ms1.5 ms
Convert a 1 MB binary body70 ms1.1 ms
Quote 64 KB of hostile text7.7 ms0.1 ms
Convert, 50 headers192 µs114 µs
Convert, simple GET5.1 µs3.2 µs

Apple M5 Pro. Same output, byte for byte: quoting was quadratic in 0.3.0.

Install

One package, no dependencies.

Package.swift
dependencies: [
  .package(url: "https://github.com/mackoj/swift-curl.git", from: "0.3.1"),
],
targets: [
  .target(name: "MyTarget", dependencies: [
    .product(name: "SwiftCURL", package: "swift-curl"),
  ]),
]
Anywhere
import SwiftCURL

let shell = try request.curl()
let line = request.curlDescription  // for logs

Swift 6.0 or later. macOS 13, iOS 16, tvOS 16, watchOS 9, visionOS 1, and Linux. Read the README for every conversion option and the full behaviour table.