Search code examples
shellrestgroovytinkerpopgremlin-server

Send groovy script as a file to the Gremlin Server REST API


Here it is explained how I can interact with a Gremlin Server using its REST API. With the following command I execute the rather simple 100-1 script.

curl -X POST -d "{\"gremlin\":\"100-1\"}" "http://localhost:8182"

What I want is to instead of using an inline script, define it in say, script.groovy.

I can make it work for this case defining a variable with the entire script:

GROOVY_LOAD_DATA_SCRIPT=$(<script.groovy)
curl -X POST -d "{\"gremlin\":\"${GROOVY_LOAD_DATA_SCRIPT}\"}" "http://localhost:8182"

But as soon as I start moving beyond one-liners that command breaks:

{
    "message": "body could not be parsed"
}

Solution

  • I created a file called send.groovy that contains:

    {
        "gremlin": "x=1+1;x+3"
    }
    

    I then send it via curl with:

    $ curl -X POST --data-binary @send.groovy http://localhost:8182/gremlin
    {"requestId":"6c0e7f3a-a16c-4fc1-a636-d462dc02b832","status":{"message":"","code":200,"attributes":{}},"result":{"data":[5],"meta":{}}}
    

    If you want multi-line in the script itself, then you have encode the contents so that it remains valid JSON (i.e. change your line breaks to "\n" since JSON doesn't allow line-breaks).

    Note that you can use tools like Python to turn the file contents into valid JSON:

    $ cat /tmp/foo
    println "Hello " + 'World!'
    1+2
    
    $ echo "{\"gremlin\":$(python -c 'import json, sys; print(json.dumps(sys.stdin.read()))' < /tmp/foo)}"
    {"gremlin":"println \"Hello \" + 'World!'\n1+2\n"}