The Swift runtime on Apache OpenWhisk does provide the following libraries pre-installed:
The Kitura-net
library provides a higher-level API for making HTTP requests than Swift's networking primitives (URLSession).
Here's an example of using that library to return data from an external JSON API as the function response.
import KituraNet
import Foundation
import SwiftyJSON
func httpRequestOptions() -> [ClientRequest.Options] {
let request: [ClientRequest.Options] = [
.method("GET"),
.schema("https://"),
.hostname("api.coindesk.com"),
.path("/v1/bpi/currentprice.json")
]
return request
}
func currentBitcoinPricesJson() -> JSON? {
var json: JSON = nil
let req = HTTP.request(httpRequestOptions()) { resp in
if let resp = resp, resp.statusCode == HTTPStatusCode.OK {
do {
var data = Data()
try resp.readAllData(into: &data)
json = JSON(data: data)
} catch {
print("Error \(error)")
}
} else {
print("Status error code or nil reponse received from App ID server.")
}
}
req.end()
return json
}
func main(args: [String:Any]) -> [String:Any] {
guard let json = currentBitcoinPricesJson() else {
return ["error": "unable to retrieve JSON API response"]
}
guard let rate = json["bpi"]["USD"]["rate_float"].double else {
return [ "error": "Currency not listed in Bitcoin prices" ]
}
return ["bitcoin_to_dollars": rate]
}
HTTP requests can be still be manually made using Swift's low-level networking primitives.