Convert cUrl command to HTTP Request in Swift
Asked Answered
D

1

6

I am building an app that checks domain availability. Right now, I am using the goDaddy API; according to goDaddy, the way to check URL availability is by the following cURL command:

curl -X GET -H "Authorization: sso-key {API_KEY}:{API_SECRET}" "https://api.godaddy.com/v1/domains/available?domain=example.guru"

Right now, I am trying to translate that cURL command to Swift. I am using Alamofire; however, when I make a request, an error as the following shows up:

Credentials must be specified

I was wondering how to solve this problem. Here is my current code:

class ViewController: UIViewController {

    let key = "KEYKEYKEY"
    let secret = "SECRETSECRET"

    var headers: HTTPHeaders = [:]

    override func viewDidLoad() {
        super.viewDidLoad()

        let credential = URLCredential(user: key, password: secret, persistence: .forSession)

        Alamofire.request("https://api.godaddy.com/v1/domains/available?domain=example.guru")
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                debugPrint(response)
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
Damiano answered 5/7, 2017 at 14:57 Comment(2)
Set the key/secret into headers instead? Also, there is no "sso-key" in yours I think.Ammonify
Alamofire.request("api.godaddy.com/v1/domains/available?domain=example.guru", headers: [String(format: "Authorization: sso-key %@:%@", key, secret)]).responseJSONProcter
C
5

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
Chemise answered 6/7, 2017 at 16:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.