REST API

Models deployed to ScienceOps can be queried using a standard REST API post request.

Code snippets below demonstrate how this can be done:

Route

  https://<SCIENCEOPS_URL>/<username>/models/<name>

Make a prediction using <username> and the models <name>.

Authentication

  • HTTP headers

Parameters:

  • username: Your username (e.g. kermit, kermit@themuppets.com)
  • name: The name of your deployed model (e.g. HelloWorld)
  • data: Data required to make 1 prediction. This is sent in the request body as JSON (e.g. {"name": "Kermit"})
  • non_vectorized (optional): If non_vectorized=true, the response values will not be arrays (NOTE: applies to R models only)
curl -X POST -H "Content-Type: application/json" \
    --user kermit:abcd123456789 \
    --data '{"name":"hank"}' \
    https://sandbox.yhathq.com/kermit/models/HelloWorld/

# {"result":{"greeting":"Hello hank!"},
# "version":5,
# "yhat_id":"20df311a254c2c08d6e04af0da941312",
# "yhat_model":"HelloWorld"}
import requests

data = '''{"name":"hank"}'''

#Post request body with basic auth
r = requests.post('https://sandbox.yhathq.com/kermit/models/HelloWorld', data=data, auth=('kermit', 'abcd123456789'))

#Print response
print(r.text)

# {"result":{"greeting":"Hello hank!"},
# "version":5,
# "yhat_id":"20df311a254c2c08d6e04af0da941312",
# "yhat_model":"HelloWorld"}
library(httr)

url <- "https://sandbox.yhathq.com/kermit/models/HelloWorld"
data <- '{"name":"hank"}'

#Make request
resp <- httr::POST(url,
  body = data,
  config = c(
    #Set basic auth
    httr::authenticate("kermit", "abcd123456789", "basic"),
    httr::add_headers("Content-Type" = "application/json")
    )
)

#Show response
paste(content(resp))

# {"result":{"greeting":"Hello hank!"},
# "version":5,
# "yhat_id":"20df311a254c2c08d6e04af0da941312",
# "yhat_model":"HelloWorld"}
require 'net/http'
require 'uri'
require 'json'

url = URI('https://sandbox.yhathq.com/kermit/models/HelloWorld/')
#Create new request
req = Net::HTTP::Post.new(url.path)
#Encode basic auth
req.basic_auth "kermit", "abcd123456789"
#Add JSON to request body
req.body = {"name":"hank"}.to_json

#Make request
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
puts resp.body

# {"result":{"greeting":"Hello hank!"},
# "version":5,
# "yhat_id":"20df311a254c2c08d6e04af0da941312",
# "yhat_model":"HelloWorld"}
package main

import (
    "net/http"
    "strings"
    "io"
    "os"
)

func main() {
    url := "https://sandbox.yhathq.com/kermit/models/HelloWorld/"
    body := strings.NewReader(`{"name":"hank"}`)

    //Construct request
    req, err := http.NewRequest("POST", url, body)
    if err != nil {
        panic(err)
    }

    //Encode basic auth
    req.SetBasicAuth("kermit","abcd123456789")
    req.Header.Set("Content-Type", "application/json")

    //Make request
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    //Print server response
    io.Copy(os.Stdout, resp.Body)
}

// {"result":{"greeting":"Hello hank!"},
// "version":5,
// "yhat_id":"20df311a254c2c08d6e04af0da941312",
// "yhat_model":"HelloWorld"}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

import javax.net.ssl.HttpsURLConnection;

public class OpsRequest {

    public static void main(String[] args) throws Exception {

        String username = "kermit";
        String apikey = "abcd123456789";
        String input = "{\"name\":\"hank\"}";

        // Encode basic auth
        Base64.Encoder encoder = Base64.getEncoder();
        String auth = encoder.encodeToString((username + ":" + apikey).getBytes());

        // Construct request
        URL obj = new URL("https://sandbox.yhathq.com/kermit/models/HelloWorld/");
        HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Basic " + auth);

        // Send post body
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(input);
        wr.flush();
        wr.close();

        // Read output
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // Print result
        System.out.println(response.toString());

    }
}

// {"result":{"greeting":"Hello hank!"},
// "version":5,
// "yhat_id":"20df311a254c2c08d6e04af0da941312",
// "yhat_model":"HelloWorld"}
<?php
$postData = json_decode("{\"name\":\"hank\"}");
$ch = curl_init('https://sandbox.yhathq.com/kermit/models/HelloWorld/');

curl_setopt_array($ch, array(
  CURLOPT_POST => TRUE,
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_USERPWD => 'kermit' . ':' . 'abcd123456789',
  CURLOPT_POSTFIELDS => json_encode($postData)
));

$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
  die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
echo json_encode($responseData, JSON_PRETTY_PRINT);
>

// {"result":{"greeting":"Hello hank!"},
// "version":5,
// "yhat_id":"20df311a254c2c08d6e04af0da941312",
// "yhat_model":"HelloWorld"}
{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

var url = 'https://sandbox.yhathq.com/kermit/models/HelloWorld'

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Basic' + btoa('kermit' + 'abcd123456789'));

request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        var data = JSON.parse(request.responseText);
        console.log(data);
    } else {
        console.log("Error calling model.");
    }
}

request.onerror = function() {
    alert("There was a connection error.");
};

var data = {
  "name": "Kermit the Frog"
}
data = JSON.stringify(data)

request.send(data);

results matching ""

    No results matching ""