You are on page 1of 16

Splunk Enterprise 6.2.

REST API Tutorials
Generated: 5/01/2015 2:00 am

Copyright (c) 2015 Splunk Inc. All Rights Reserved

Table of Contents
REST API tutorials...............................................................................................1
Accessing and updating Splunk Enterprise configurations.......................1
Creating searches using the REST API.....................................................6
Examples using the Splunk REST API...................................................12

REST API tutorials

Accessing and updating Splunk Enterprise
This section describes how to use the Splunk Enterprise REST API to access
and update information contained in configuration files (*.conf files). For more
information on configuration files, see About Configuration Files and
Configuration File Precedence in the Splunk Admin manual.
Two sets of endpoints give access to configuration files:
These endpoints do the same task for updating configurations, but their
implementation differs. In most cases, you can use properties endpoints for
updating configurations. But, there are times where you can use only the
configs/conf-{file} endpoints. For example, use the configs/conf-{file}
endpoints for,
Setting permissions
Enabling or disabling a stanza in a configuration
Moving a resource

Reading configuration files

The way you read configurations files differs between properties/ and
configs/conf-{file}/ endpoints.
properties endpoints
The properties set of endpoints give various options for listing configurations.
GET operations are available to drill down from the list of configuration files to the
key/value pairs.
GET properties
Returns the names of configuration files.
GET properties/{file_name}

Returns the stanza names in {file_name}.conf.

GET properties/{file_name}/{stanza_name}
Returns the key/value pairs for the named stanza.
GET properties/{file_name}/{stanza_name}/{key_name}
Returns the key value.
For example, the search/properties/props GET operation returns all the stanza
names for props.conf:

curl -k -u admin:pass

The response:

<feed xmlns=""
. . .
. . .
<link href="/servicesNS/nobody/search/properties/props/wmi"

<link href="/servicesNS/nobody/search/properties/props/wtmp"
The /search/properties/props/websphere_core GET operation returns the
key/value pairs for the props.conf file webshpere_core stanza.

curl -k -u admin:pass

The response:

<feed xmlns=""
. . .
<content type="text">True</content>
<content type="text">^NULL\s</content>
. . .
<content type="text">70</content>

configs/conf-{file} endpoints
GET operations for these endpoints return entries for the stanzas in the named
configuration file, detailing the contents of the stanza as key/value pairs.
For example, the /search/configs/conf-props GET operation lists the
props.conf configuration for the default search application.

curl -k -u admin:pass
The response, showing elided fragments of a few stanzas in props.conf.

<feed xmlns=""
. . .
. . .
<content type="text/xml">
<s:key name="ANNOTATE_PUNCT">1</s:key>
<s:key name="BREAK_ONLY_BEFORE"></s:key>
<s:key name="BREAK_ONLY_BEFORE_DATE">1</s:key>
. . .
<s:key name="maxDist">28</s:key>
<s:key name="pulldown_type">1</s:key>
. . .
. . .
<content type="text/xml">
<s:key name="ANNOTATE_PUNCT">1</s:key>
<s:key name="BREAK_ONLY_BEFORE"></s:key>
<s:key name="BREAK_ONLY_BEFORE_DATE">1</s:key>
. . .
<s:key name="eai:appName">search</s:key>
<s:key name="eai:userName">nobody</s:key>

<s:key name="maxDist">100</s:key>

Updating Configuration Files

You update a configuration file by adding or editing stanzas to the file. How you
do this differs between properties and configs/conf-{file} endpoints. Do
DELETE operations from only the configs/conf-{file} endpoints.
The DELETE operation is available from the properties endpoint, but is
deprecated. Instead, use the DELETE operations from configs/conf-{file}
When you update a configuration, updates are written to the local version of the
file. The default version of configurations can be overwritten when you update
Splunk to a new version.
Use the POST operation with various properties endpoints to update
configuration files.
Use DELETE operations from the configs/conf-{file} endpoints.
Use the POST operation to add a stanza to the named configuration file. You can
also specify key/value pairs for the newly added stanza. For example, the
/search/configs/conf-props POST operation creates a new stanza and
key/value pairs in props.conf for the default search application.

curl -k -u admin:pass
https://localhost:8089/servicesNS/nobody/search/configs/conf-props \
-d name=myweblogs \

Use the POST operation to create or update key/value pairs in the {name}
Use the DELETE operation to remove a stanza from a configuration file.

Creating searches using the REST API

Use the search/jobs endpoint to create a search job in Splunk. However, before
creating searches you should be aware of how searches work and how to
structure a search so you can easily access the results.

Learn about searches

The best place to learn about searches and how to write searches is the Search
Here are some highlights from the Search Reference that can help you get
started creating searches:
Search command cheat sheet Quick command reference complete with
descriptions and examples.
Write better searches Provides some simple rules of thumb and best
practices to help you write searches that run more efficiently.
Popular search commands A list describing the more frequently used
search commands.
Execution costs Describes how to troubleshoot the efficiency of a search.
Search job properties Lists and defines the properties of a search job.
Search Command Reference Complete syntax of Splunk search

REST endpoints for searches

Here is a brief description of some of the key endpoints for creating and
accessing searches.
Create or access the results of search jobs. Returns a search ID (sid) that you
use when accessing the results of a search.
Stream search results as they become available. Does not create a search ID for
later access.
Execute a job control command for a search, such as pause, setpriority, or

Return untransformed events of a search.
Return transformed events of a search.
Return summary information for fields of a search.
Return event distribution over time of the so-far-read untransformed events.
Create or access the configuration of saved searches.

Tips on creating searches

When creating a search (POST /search/jobs), consider the following properties of
the search:
Set this parameter for searches returning more than the default maximum of
10000 events. Otherwise you may not be able to retrieve results in excess of the
To access summary and timeline information from a search job, specify a value
for status_buckets. The default value is zero. For example, searches spawned
from the Splunk timeline specify status_buckets=300.
Use the rf parameter to add required fields to a search. Adding fields guarantees
results for the endpoints that return events and a summary. (The
required_fields parameter has been deprecated in favor of the rf parameter.)

Tips on accessing searches

When accessing the results of a search (GET /search/jobs/{search_id}), consider
the following:
search, offset, and count parameters
Use these parameters to a GET operation to filter or limit the results returned.

is one of the properties returned when accessing a search. It
provides the state of a search, which can be any of the following:

search job properties
The GET operation for /search/jobs returns all the properties of a search. These
properties are described in the parameters to the POST operation. Search job
properties are also described in "View search job properties with the Search Job
The GET operation for /search/jobs returns information that helps you
troubleshoot the efficiency of a search. Refer to "Execution costs" in "View
search job properties with the Search Job Inspector" for more information.

Example: Create a search

Many calls to Splunk's API involve running some kind of search. For example,
you may wish to run a search within Splunk and POST the results to a third party
application. Use the endpoints located at the
../services/search/<endpoint> URIs.
When you run a search, Splunk launches a search process asynchronously. This
means that you must poll the jobs or events endpoint to see if your search has
Create a search job
Create a search job using the POST operation at search/jobs/. Set your search
as the POST payload. For example:
curl -u admin:changeme -k https://localhost:8089/services/search/jobs
-d search="search *"

This simple example runs the search for *. It returns an XML response such as:

<?xml version='1.0' encoding='UTF-8'?>


You need the search ID to retrieve the search, which is returned within the <sid>
tags. In the example above this is 1258421375.19.
Check status of a search
Check the status of a search job by accessing the GET operation of search/jobs/.
If you know the search's ID, you can access search/jobs/{search_id} to get
information about that search only:

curl -u admin:changeme -k

If you're not sure what searches you're running, the GET operation at search/jobs
endpoint returns a list of searches with their search IDs.

curl -u admin:changeme -k https://localhost:8089/services/search/jobs/

Get search results

Use the results endpoint located at /search/jobs/<sid>/results/ to retrieve your
search results. This endpoint returns results only when your search has
completed. You can also get output from the events endpoint located at
/search/jobs/{search_id}/events/ while your search is still running. For complete
search results, use the results endpoint.
You can return search results in JSON, CSV or XML by setting the output_mode
parameter. By default, results are returned in XML format.
For example, to retrieve search results in CSV format, make the following call.
Note: The curl listing includes --get because you are passing a parameter to a
GET operation.

curl -u admin:changeme \
https://localhost:8089/services/search/jobs/1258421375.19/results/ \
--get -d output_mode=csv

Note: This is one method that you can use to export large numbers of search
results out of Splunk Enterprise. For more information about exporting search

results with the REST API, as well as information about the other export methods
offered by Splunk Enterprise, see "Export search results" in the Search Manual.
Python example
Here's an example of authenticating against a Splunk server and running a
search query in Python. After running the search, the script returns the search ID

#!/usr/bin/python -u
import urllib
import httplib2
from xml.dom import minidom
baseurl = 'https://localhost:8089'
userName = 'admin'
password = 'pass'
searchQuery = 'sourcetype=access_common | head 5'
# Authenticate with server.
# Disable SSL cert validation. Splunk certs are self-signed.
serverContent =
httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl +
'POST', headers={}, body=urllib.urlencode({'username':userName,

sessionKey =
# check if the query has the search operator
if not searchQuery.startswith('search'):
searchQuery = 'search ' + searchQuery
# Run the search.
# Again, disable SSL cert validation.
httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl +
headers={'Authorization': 'Splunk %s' %
sessionKey},body=urllib.urlencode({'search': searchQuery}))[1]

Ruby example
The following example shows how to use Ruby to authenticate against the
Splunk REST API with a generic user name and password. Then, run a search,
delete a specific search job and list out available search jobs. Note that the list is

returned in XML and not parsed. To parse the results from endpoints, use an
XML parser such as libxml. Also, you'll need to install the hpricot gem to get this
to work.

require 'net/https'
require 'rubygems'
require 'hpricot'
class SplunkClient
HOST = 'localhost'
PORT = 8089
USER = 'admin'
PASSWORD = 'changeme'
def splunk_ssl_post_request(path, data = nil, headers = nil)
http =, PORT)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE, data, headers).body
def session_key
@session_key ||= load_session_key
def load_session_key
doc = Hpricot(splunk_ssl_post_request("/services/auth/login",
def create_job query
search = "search index=internetmail #{query}"
{ 'authorization' => "Splunk
#{session_key}" })
def list_jobs
xml = splunk_ssl_post_request("/services/search/jobs/", nil,
{'authorization' => "Splunk #{session_key}"})
puts xml
def search_results(sid)
doc = Hpricot(


{'authorization' => "Splunk

(doc/"/results/result").collect do | result |
log_text = (result/"field[@k='_raw']/v").inner_text log_text
def splunk_ssl_delete_request(path, headers = nil)
http =, PORT)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.delete(path, headers).body
def delete_job(sid)
{ 'authorization' => "Splunk
#{session_key}" })
# Here's the actual operating code
client =
puts client.list_jobs

Examples using the Splunk REST API

This section shows some typical use cases for the Splunk REST API. These
examples show how to use the servicesNS endpoints to access resources within
a user/app context. They also show some of the additional operations available,
such as moving an object to a different app or changing the permissions of an

Create a new Splunk object for a specific context

Create a saved search for the user Alice that is available from the app, myapp.
This saved search is private to Alice.

curl -k -u alice:pass
-d name=mysearch \
-d search=*


Edit a Splunk object

Change the above search created for Alice.
Because this search is private to Alice, she can edit the search.

curl -k -u alice:pass
https://localhost:8089/servicesNS/alice/myapp/saved/searches/mysearch \
-d search="index=mai*"

Share an object to an app, modify its permissions, and edit it

Make Alice's saved search, mysearch, available through the app, myapp. Allow
all users permissions to read the saved search.

curl -k -u admin:pass
-d* \
-d owner=alice \
-d sharing=app

Edit the search at the shared location. Because the search is now a shared
resource, use <nobody> for the <user> context.

curl -k -u alice:pass
-d search="index=main"

Move an object to a different app

The saved search that was previously available to all in the context of myapp is
now only available in the context of otherapp.

curl -k -u admin:pass
-d user=nobody \
-d app=otherapp

Access objects available in all user/app contexts

Using wildcards, access all saved searches that you have permission to view.
For an admin user, this includes other user's private saved searches.
For a non-admin user, you retrieve only saved searches you have permission to

curl -k -u admin:pass
curl -k -u alice:pw