James Thomas
James Thomas

Reputation: 4339

Making HTTP request using Swift on OpenWhisk?

How can I make HTTP requests to retrieve and return data during a serverless Swift function running on Apache OpenWhisk?

Serverless cloud platforms restrict access to the runtime environment. This means you can't install extra libraries to help with this, e.g https://github.com/Alamofire/Alamofire.

Upvotes: 0

Views: 194

Answers (1)

James Thomas
James Thomas

Reputation: 4339

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.

Upvotes: 1

Related Questions