Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Last active July 16, 2025 14:07
Show Gist options
  • Save thomsmed/37e84842bbd46d566c837f4600a067f7 to your computer and use it in GitHub Desktop.
Save thomsmed/37e84842bbd46d566c837f4600a067f7 to your computer and use it in GitHub Desktop.
A simple URLRequest extension that map the request to curl representation.
import Foundation
public extension URLRequest {
var curlRepresentation: String {
guard let url = url?.absoluteString else {
return "could not create curl command"
}
var components = ["curl \(url)"]
if let method = httpMethod, method != "GET" {
components.append("-X \(method)")
}
for (key, value) in allHTTPHeaderFields ?? [:] {
components.append("-H '\(key): \(value)'")
}
if let body = httpBody, let bodyString = String(data: body, encoding: .utf8) {
let sanitizedBody = bodyString
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "'", with: "\\'")
components.append("-d '\(sanitizedBody)'")
}
return components.joined(separator: " \\\n\t")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment