swiftrestapiauthenticationshippo

Swift 4 URLsession with Authentication API Key


I am trying to make a POST Request for the Shippo REST API in Swift, but since it needs an API Authentication key I cannot figure out how to implement the key in the URLSession in Swift 4. As the Apple documentation puts it I cannot use urlsession.shared method. The cURL command is:

curl https://api.goshippo.com/addresses/ \
 -H "Authorization: ShippoToken shippo_test_Token_Here" \
 -d name="Shawn Ippotle" \ -d company="Shippo" \
 -d street1="215 Clayton St." \
 -d street2="" \
 -d city="San Francisco" \
 -d state="CA" \
 -d zip=94117 \
 -d country="US" \
 -d phone="+1 555 341 9393" \
 -d email="shippotle@goshippo.com"\
 -d is_residential=True\
 -d metadata="Customer ID 123456"

Solution

  • Here it is using Alamofire. I hope this helps. I have tested it and it works.

    func mainRequest(){
    
        var headers: HTTPHeaders = [
            "content-type": "application/json"
        ]
    
        let credentials = "shippo_test_8dc780c66d5dae1c42868596c0b359ba89108df9"
        headers["Authorization"] = "ShippoToken \(credentials)"
    
        var parameters:Parameters = [String : Any]()
    
        parameters["name"] = "Shawn Ippotle"
        parameters["company"] = "Shippo"
        parameters["street1"] = "215 Clayton St."
        parameters["street2"] = ""
        parameters["city"] = "San Francisco"
        parameters["state"] = "CA"
        parameters["zip"] = "94117"
        parameters["phone"] = "+1 555 341 9393"
        parameters["country"] = "US"
        parameters["email"] = "shippotle@goshippo.com"
        parameters["is_residential"] = "True"
        parameters["metadata"] = "Customer ID 123456"
    
        let url = "https://api.goshippo.com/addresses"
    
        Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
            .responseJSON { (response) in
                switch response.result {
                case .success(let value):
                    let swiftyJson = JSON(value)
                    print ("return as JSON using swiftyJson is: \(swiftyJson)")
                case .failure(let error):
                    print ("error: \(error)")
                }
    
        }
    }