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 https://xms.example.com/api/json/v2/types/volumes)

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

#!/bin/bash

#
# 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
        fi

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

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

        cat $TMPFILE
        rm $TMPFILE

        return $RESP
}

Response=$(API admin Xtrem10 POST https://xms.example.com/api/json/v2/types/snapshots '{"from-consistency-group-id":"CG1","to-snapshot-set-id":"SS1","no-backup":"true"}')

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