ApacheのOpenWhisk上スウィフトランタイムは以下のライブラリプリインストールを提供しません:
Kitura-net
ライブラリは、Swiftのネットワークプリミティブ(URLSession)よりもHTTP要求を行うためのより高いレベルのAPIを提供します。
ここでは、そのライブラリを使用して外部JSON APIからのデータを関数レスポンスとして返す例を示します。
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リクエストは、Swiftの低レベルネットワークプリミティブを使用して手動で作成できます。