How to Convert Curl Command to Swift

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.

How to convert CURL command to Swift

I would say that you should use the API that Proliphix is providing.

As you can see, they provide an example, and you've already managed to figure out how to provide the correct parameters through cURL so now you "just" need to convert this to Swift.

For this you need a HTTP networking API, you could use either the NSURLSession API provided by Apple, or perhaps Alamofire, just to mention a pair.

These API's take an URL which would be /get or /pdp in your case. Then you need to tell them wether this is a GET or a POST request. If the API needs any data (like the OID parameters in your case), you'll need to provide that as well and then you need to set up eventual headers.

Then you send your request and wait for an answer, which you then react to.

Here is an example on how to do this with NSURLSession:

if let url = NSURL(string: "http://httpbin.org/post"){
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST" //Or GET if that's what you need
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //This is where you add your HTTP headers like Content-Type, Accept and so on
let params = ["OID1.2" : "SW+Dev+114", "OID1.4" : "192.168.111.114"] as Dictionary<String, String> //this is where you add your parameters

let httpData = NSKeyedArchiver.archivedDataWithRootObject(params) //you need to convert you parameters to NSData or to JSON data if the service accepts this, you might want to search for a solution on how to do this...hopefully this will get you in the right direction :-)
request.HTTPBody = httpData
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: { (returnData, response, error) -> Void in
var strData = NSString(data: returnData, encoding: NSUTF8StringEncoding)
println("\(strData)")
}).resume() //Remember this one or nothing will happen :-)
}

Hope this gets you in the right direction. You could also do a Google search for NSURLSession or Alamofire tutorial, now that you know what to search for.

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 Command to swift using Alamofire

In your code you are using method: .post, where it is not needed. Also there are some wrong parameter names (e.g. "ClientID": clientID should be renamed to "client_id": clientID). This might be a cause of 400 or 404 status codes.

At least this GET request worked for me without 400 or 404 status codes:

Alamofire
.request(
"https://api.everypixel.com/oauth/token",
parameters:[
"client_id" : clientID,
"client_secret" : clientSecret,
"grant_type" : "client_credentials"
]
)
.responseString { response in
switch response.result {
case .success(let value):
print("from .success \(value)")
case .failure(let error):
print(error)
}
}

How to convert CURL request to Swift using Alamofire?

It looks like you want to set header Authorization to DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv". You can do that like this:

let loginToken = "DirectLogin token=\"eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv\""

...

@IBAction func callAPIAction(_ sender: Any) {
Alamofire
.request(
self.url,
headers: [
"Authorization": self.loginToken,
"Content-Type": "application/json"
]
)
.responseString {
response in
switch response.result {
case .success(let value):
print("from .success \(value)")
case .failure(let error):
print(error)
}
}
}

...

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)


Related Topics



Leave a reply



Submit