URLRequest in,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.
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))
curl 'https://api.example.com/users' \ -H 'Content-Type: application/json' \ --data-raw '{"name":"O'\''Brien"}'
The problem
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.
let header = "-H \"\(name): \(value)\"" let body = "-d '\(text)'"
$HOME, $(…) and backticks from header values.-d @file makes curl read a local file; -X HEAD hangs waiting for a body.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'
' becomes '\''.--data-raw, so a leading @ is never a file name.base64 --decode, byte-exact.What you get
Conversion produces a CURLCommand: inspect it, append options, read the exact argv curl
will receive, then render it the way you want.
One quoting function, single quotes only. The only $ ever emitted is a variable you asked for.
Architecture rules keep it that way.
ShellSubstitution writes a token as "$API_TOKEN", even when it appears base64 or
percent-encoded. Share the command, not the credential.
request.curlDescription redacts Authorization, cookies and API keys, omits binary and
streamed bodies, and degrades to an inert shell comment.
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.
-I for HEAD, no redundant -X, -g for URLs with brackets,
--url for URLs starting with -, Name; for empty header values.
Sendable, Hashable and Codable models, typed throws, Foundation only.
macOS, iOS, tvOS, watchOS, visionOS and Linux.
Examples
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"
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')"
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'
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 '@-'
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
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.ShellEscaping writes quoting, if a $ appears
outside ShellSubstitution, or if a value is ever left unquoted.
All rules.| Release build, p50 | 0.3.0 | 0.3.1 |
|---|---|---|
| Render a 1 MB JSON body | 172 ms | 1.5 ms |
| Convert a 1 MB binary body | 70 ms | 1.1 ms |
| Quote 64 KB of hostile text | 7.7 ms | 0.1 ms |
| Convert, 50 headers | 192 µs | 114 µs |
| Convert, simple GET | 5.1 µs | 3.2 µs |
Apple M5 Pro. Same output, byte for byte: quoting was quadratic in 0.3.0.
Install
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"), ]), ]
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.