OK, this exercise is done. Here are my steps:
- Create an application named test_rest_api.
- Create the following stanza in $SPLUNK_HOME/etc/system/local/web.conf:
[expose:test_rest_api]
methods = GET
pattern = test_rest_api/test
Create the following stanza in $SPLUNK_HOME/etc/system/local/restmap.conf:
[script:testRestApi]
match = /test_rest_api/test
scripttype = python
handler = test_rest_script.MyImageHandler
requireAuthentication = false
Create a python script named test_rest_script.py in etc/apps/test_rest_api/bin folder). Here is the entire script:
import splunk
import splunk.rest as rest
import splunk.entity as entity
import splunk.auth
import splunk.models.dashboard as sm_dashboard
import splunk.models.dashboard_panel as sm_dashboard_panel
import splunk.models.saved_search as sm_saved_search
import splunk.search
import splunk.search.searchUtils
from splunk.util import normalizeBoolean
import os, sys
class MyImageHandler(splunk.rest.BaseRestHandler):
TEST_API_BINARY_MODE = 'binary'
BINARY_FILE_NAME = '../etc/apps/test_rest_api/appserver/static/rubber-duck.jpg' # relative to $SPLUNK_HOME/bin
message = 'Test <strong>REST</strong> API'
status = 200
def handle_GET(self):
if self.TEST_API_BINARY_MODE in self.args and self.args.get(self.TEST_API_BINARY_MODE) in ('true', 'True', 'y', 'yes', '1'):
self._binResponse()
else:
self._textResponse()
def _textResponse(self):
self.response.write(self.message)
self.response.setStatus(self.status)
self.response.setHeader("content-type", "text/html")
def _binResponse(self):
try:
data = self._getImage()
self.response.write(data)
self.response.setStatus(self.status)
self.response.setHeader('content-type','image/jpg')
except Exception as e:
self.message = str(e)
self.status = 501
self._textResponse()
def _getFileName(self):
scriptname = os.path.abspath(sys.argv[0])
scriptdir = os.path.dirname(scriptname)
imgname = os.path.normpath('/'.join([ scriptdir, self.BINARY_FILE_NAME ]))
return imgname
def _getImage(self):
imgname = self._getFileName()
f = open(imgname, 'rb')
data = f.read()
f.close()
return data
Why is sys.argv[0] returning a $SPLUNK_HOME/bin folder rather than etc/apps/test_rest_api/bin, I don't know, but it's used for testing purposes only (I've put that rubber-duck.jpg in my app's appserver/static). My real script will read the image from an http link :).
So you just enter https://localhost:8089/services/test_rest_api/test?binary=true and enjoy the picture of the rubber duck! Or omit that binary parameter (or, say, put 'false' there) and look at the proud 'Test REST API' message.
... View more