Although Swift is generally known to be a client-side language, it is fast becoming the language for your server-side needs. Swift is fast, type-safe, modern and contains a vast set of libraries that reduce the effort of writing code.

Swift is now available as a server-side language on the zSeries mainframe with the Swift on z/OS IBM Toollkit.

REST APIs

This article demonstrates how to call REST API web services via Swift. Typical REST API calls are performed via an HTTP request which respond with a JSON output. REST API calls are becoming the standard way to expose interfaces across services. IBM provides many REST services such as z/OS Connect APIs, IBM’s Weather Channel REST API, and much more.

This example will demonstrate how to retrieve the temperature of a given city and state using the Weather Channel API and Swift.

To reproduce this example, you must register at http://api.wunderground.com/api/ to generate a weather API key. Developer API keys are free for a limited number of API requests.

Perform a HTTP Request on a REST API

The swift language ships with many useful collections and libraries that aid your development.

Initially, what we will do is create a dictionary of cities and their states/provinces as such:

var cities : [String: String] = ["New_York": "NY", "San_Francisco": "CA", "Toronto": "Ontario"] 

Swift allows you to easily loop through a dictionary using for(key, value) construct as such:

for (city, state) in cities 

For each iteration, we will make a URL Request to the REST API endpoint using the following string:

let urlString = http://api.wunderground.com/api/\(weather_key)/conditions/q/\(state)/\(city).json 

Swift using string interpolation to replace the weather_key, state, and city variables in the string above.

The following Swift code will implement the REST API call in Swift

//rest.swift
import Foundation

let weather_key = "ENTER_YOUR_KEY_HERE"

var cities : [String: String] = ["New_York": "NY", "San_Francisco": "CA", "Toronto": "Ontario"]
for (city, state) in cities {
    let cond = NSCondition()
    let urlString = "http://api.wunderground.com/api/\(weather_key)/conditions/q/\(state)/\(city).json"
    let url = URL(string: urlString)!
    let getRequest = URLRequest(url: url)
    let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)
    let task = session.dataTask(with: getRequest) { data, response, error in
            if let data = data {                                                                                                                                                                                            if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
                    let json1 = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                    if let json = json1 {
                        let obs = json["current_observation"] as! [String:Any]
                        let temperature = obs["temperature_string"]!
                        print("The temperoature at \(city) is \(temperature)")
                    }
                } else {
                    print("Error \(response)");
                }
            }
            cond.broadcast();
            cond.unlock()
    }
    cond.lock()
    task.resume()
    cond.wait()
}

The JSONSerialization.jsonObject parses the data into dictionary and then we access the temperature_string in the dictionary and display it to the console.

To compile and run use: swiftc rest.swift && ./rest

You should receive a response as follows:

The temperature at Toronto is 19.8 F (-6.8 C) 
The temperature at New_York is 30.7 F (-0.7 C) 
The temperature at San_Francisco is 30.7 F (-0.7 C) 

Resources

Swift on zOS: https://developer.ibm.com/swift/2016/12/05/try-swift-on-zos/
IBM Toolkit for Linux on zhttps://www.ibm.com/us-en/marketplace/swift-compiler
Weather API: https://github.com/initialstate/wunderground-sensehat/wiki/Part-1.-How-to-Use-the-Wunderground-API






Join the discussion on Slack Learn more at kitura.io Star Kitura on GitHub

Join The Discussion

Your email address will not be published. Required fields are marked *