cancel
Showing results for 
Search instead for 
Did you mean: 

Py Script snap

munish
New Contributor

I am building a pipeline which need to make recurring API call and consolidate the result. But when I call the API inside py script snap then it does not return result as the API default result. I tried to use two methods of get as get.getResponseBodyAsString() and get.getResponseBody()
get.getResponseBodyAsString() → return response as string
get.getResponseBody() → returns “Base64 encoded data”

So I am stuck here, where I need the result in json format which is default API response type, but it is creating issue. Below is the code for this.

from com.snaplogic.scripting.language import ScriptHook
from com.snaplogic.scripting.language.ScriptHook import *

from org.apache.commons.httpclient import HttpClient
from org.apache.commons.httpclient.methods import GetMethod;

class UploadScript(ScriptHook):
def init(self, input, output, error, log):
self.input = input
self.output = output
self.error = error
self.log = log

def execute(self):
    while self.input.hasNext():
        data = self.input.next()
        url = "https://gorest.co.in/public-api/products"
        get = GetMethod(url)
        client = HttpClient()
        r = client.executeMethod(get)
        #s = get.getResponseBodyAsString()
        s = get.getResponseBody()
        t = get.getStatusText()
        h = get.getResponseHeaders()
        self.output.write(s)
   self.log.info("Finished executing the upload script")

hook = UploadScript(input, output, error, log)

3 REPLIES 3

mbowen
Employee
Employee

What error do you get when you try to import the “json” lib? The Script snap uses Jython 2.7.2 which seems to support json, however, I’m not so sure about numpy.

I was able to add “import json” to your script, and could then parse the json string with json.dumps(). Similarly, I could convert dict to a json string with json.dumps (ie, json.dumps(py_dict)).

def execute(self):
    while self.input.hasNext():
        data = self.input.next()
        url = "https://gorest.co.in/public-api/products"
        get = GetMethod(url)
        client = HttpClient()
        r = client.executeMethod(get)
        s = get.getResponseBodyAsString()
        py_dict = json.loads(s)
        t = get.getStatusText()
        h = get.getResponseHeaders()
        self.output.write(py_dict)
    self.log.info("Finished executing the upload script")

For numpy, I assume you are getting an import error? Jython 2.7.2 seems to offer some support for this library, and uses Jython Native Interface (JyNI) to access the Numpy c library. I’m less familiar with our Python scripting support and would need to investigate this.

munish
New Contributor

Hey Mathew,
Thanks for reply. I want to add a column in existing resultset that is array. and it is all in python. If you can help me for that?

Thanks

Why use a python script instead of our REST Get snap?