Swift

Getting Started

The Terrene API is organized around REST. Our API has predictable, resource-oriented URLs, and uses HTTP response codes to indicate API errors. We use built-in HTTP features, like HTTP authentication and HTTP verbs, which are understood by off-the-shelf HTTP clients. We support cross-origin resource sharing, allowing you to interact securely with our API from a client-side web application (though you should never expose your secret API key in any public website's client-side code). JSON is returned by all API responses, including errors, although our API libraries convert responses to appropriate language-specific objects.

In this tutorial, you'll learn how to use a model trained by Terrene in your Swift app. If you haven't already trained a model on Terrene, please refer to one of the model training tutorials and then come back here once you're done.

1. Create an Authentication Token

To access Terrene's API, first create an authentication token in Terrene's portal. To do so click on the settings icon in the top toolbar of the dashboard.

workspace dashboard profile pointer

Then click on the account security tab and then generate a new authentication token.

generate new authentication token

Copy and store your newly created authentication token.

save new authentication token

2. Find The Unique Identifier of Your Predictive Endpoint

On the workspace page in Terrene's portal, click on the "Model Endpoints" option from the left menu then click on the predictive endpoint which you want to use.

workspace dashboard

Then find and save the object_id of your predictive endpoint.

workspace dashboard

3. Make a HTTP Request

Terrene uses JSON Web Tokens to authenticate your HTTP requests. The JWT must to be passed as an Authorization header with the format of JWT <token>.

// Set to your predictive model's object_id from step 2
let predictive_endpoint = ""

// Set to your authentication token from step 1
let authentication_token = ""

In order to make a prediction, you need to json serialize your input dictionary. Please make sure the key names in your dictionary match the input variables for your predictive model.

let input_data: [String: Any] = ["input_json" :[
    "Pclass": 1,
    "Sex": "male",
    "Age": 32,
    "SibSp": "0",
    "Parch": "0",
    "Cabin": "C30"
]]
let input_data_json = try JSONSerialization.data(withJSONObject: input_data)

Now you can construct your HTTP request.

let request_url = URL(string: "https://api.terrene.co/serve/" + predictive_endpoint + "/predict/")!
var request = URLRequest(url: request_url)
request.httpMethod = "POST"
request.httpBody = input_data_json
print(input_data_json)
request.addValue("JWT " + authentication_token, forHTTPHeaderField: "Authorization")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")

Now that the HTTP request is constructed, you can go ahead an run it.

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}
task.resume()

Conclusion

Here's the completed code for your reference:

// Set to your predictive model's object_id from step 2
let predictive_endpoint = ""

// Set to your authentication token from step 1
let authentication_token = ""

let input_data: [String: Any] = ["input_json" :[
    "Pclass": 1,
    "Sex": "male",
    "Age": 32,
    "SibSp": "0",
    "Parch": "0",
    "Cabin": "C30"
]]
let input_data_json = try JSONSerialization.data(withJSONObject: input_data)

let request_url = URL(string: "https://api.terrene.co/serve/" + predictive_endpoint + "/predict/")!
var request = URLRequest(url: request_url)
request.httpMethod = "POST"
request.httpBody = input_data_json
print(input_data_json)
request.addValue("JWT " + authentication_token, forHTTPHeaderField: "Authorization")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}
task.resume()