How to Perform a Curl Request in Swift

How to do a curl request in Swift?

I think the problem is with the array parameter requested_capabilities.
Whe using JSON, you don't suffix the square bracktes to the key ( requested_capabilities[]) like in curl. Instead, you write the value(s) in square brackets, like here:

let payload =  "{\"country\":\"US\",\"type\":\"custom\",\"requested_capabilities\":[\"card_payments\"]}"

or, more readable:

let payload = """
{
"country" : "US",
"type" : "custom",
"requested_capabilities" : ["card_payments"]
}
"""

Nevertheless, if you are using hard-coded JSON and maybe want to insert some variable data into the structure, be very careful to prevent Bobby-Tables-Attacks.

Convert cUrl command to HTTP Request in Swift

I know that this is not using Alamofire but this is how I would achieve it.

import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"

let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}

let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true

Convert CURL to Swift

Let's analyze your cURL command, let's make it more readable with breaking line. If you want to make it working as such in Terminal.app, just add \ at the end of the line.

curl \
-X POST \
"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" \
-H "Ocp-Apim-Subscription-Key: <client-secret>" \
-H "Content-Type: application/json; charset=UTF-8" \
-d "[{'Text':'Hello, what is your name?'}]"

-H: Set with addValue(_,forHTTPHeaderField:)
-d: Set it with httpBody =
The long URL, that's request.url

There are two main differences between the cURL command and the URLRequest you mode.

First, you did mix payload & URL settings.

url should be "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn", not "https://api.cognitive.microsofttranslator.com/translate", you put api-version, to, toScript (that one is missing by the way) inside httpBody.
Put them into the URL instead. You can use URLQueryItem to format them correctly. See related question.

Now, once you fix that, there is a second issue:

[{'Text':'Hello, what is your name?'}], I'll by pass the strange fact that it's using single quotes, but, here JSON is an array at top level, not a dictionary. Also, it's Text, not text (it might be case sensitive).

If you want to see what you are sending in httpBody, do not hesitate to do:

if let jsonStr = String(data: request.httpBody ?? Data(), encoding: .utf8) {
print("Stringified httpBody: \(jsonStr)")
}

So fix your parameters until it matches the on in the working cURL command. As said, it's an array, not a dictionary.

Finally, avoid using try?, please do proper do/try/catch because if it fails, at least you need to know about it.

No need to use .allowFragments if you don't expect a JSON String at top level. Here you are expecting a Dictionary.

And I'd recommand to use Codable now in Swift 4+ instead of JSONSerialization.

Edit: Seeing the doc, as you mixed the parameters/query, keep in mind:
"Query Parameters", that's for URLQueryItems and it's in the URL.
Request Body: That's for the httpBody.

Converting curl to URL request in Swift

You're adding the binary data as a header, instead you should convert the string to data and add it to the httpBody property of the request.

request.httpBody = "YOUR STRING HERE".data(using: .utf8)

Swift - Convert URLRequest to cURL

You can simply try this
URLRequest to cURL

To use it in your code first import that extension and then simply call urlRequest.cURL() or urlRequest.cURL(pretty: true) to print pretty formatted curl.

EDIT: Now the above gist has Alamofire support also



Related Topics



Leave a reply



Submit