REST API Scripting with curl

I've stated previously that using curl for accessing the XtremIO REST API (or any API!) isn't ideal as it's difficult to handle errors returned by the API.

Below is a BASH function that can help with this. It takes the options for a REST API call, and returns an error if either the curl/network/etc side of things fails, OR if the REST API returns an error.

Using it is as simple as calling the function with the relevant parameters, and then checking the return value to see if the API call was successful or not.

eg :

Response=$(API admin Xtrem10 GET

The full API function, along with an example, is included below. You can also get it from here


# The API function will initiate a REST API call to the XtremIO XMS with
# error checking.
# Usage :
#    API username password req_type URL req_body
#      username - The username to use to authenticate to the XMS (eg, admin)
#      password - The password to use to authenticate to the XMS
#      req_type - One of GET, POST, PUT or DELETE
#      URL      - The full URL to the resources
#      req_body - For POST/PUT, the JSON-formatted body of the request
# The function returns 0 if the request is successful, and the JSON response
# from the array (if any) is send to stdout, otherwise it returns non-zero.
API() {

        local TMPFILE=`mktemp`
        local BODY=""

        if [ $# -eq 5 ]; then
                BODY="-d ${5}"
        elif [ $# -ne 4 ]; then
                echo Invalid number of arguments past to API
                return 99

        local RESP=$(curl -s --output $TMPFILE --write-out "%{http_code}" -X ${3} ${BODY} -u ${1}:${2} -k -s ${4})

        if [ $? -ne 0 ]; then
        elif [ $RESP -ge 200 ] && [ $RESP -le 299 ];  then

        cat $TMPFILE
        rm $TMPFILE

        return $RESP

Response=$(API admin Xtrem10 POST '{"from-consistency-group-id":"CG1","to-snapshot-set-id":"SS1","no-backup":"true"}')

if [ $? -eq 0 ]; then
        echo SUCCESS.  Response was :
        echo $Response
        echo ERROR.  Error was :
        echo $Response