Splunk Enterprise API Client Code Examples¶
This guide shows how to use the
SplunkEnterprise client to interact with Splunk Enterprise APIs.
- Wingpy handles authentication, pagination and error management for you.
The Basics - Connect and Retrieve Data¶
Environment Variables
You can set the environment variables in your shell to avoid hardcoding sensitive information in your code. Check out the FAQ section on Environment Variables for more details.
from wingpy import SplunkEnterprise
splunk = SplunkEnterprise(
base_url="https://splunk.example.com", # (1)!
username="admin", # (2)!
password="password", # (3)!
verify=False,
)
- Environment variable:
- Environment variable:
- Environment variable:
The Splunk API's native data format is XML.
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:s="http://dev.splunk.com/ns/rest" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
<entry>
<content type="text/xml">
<s:dict>
<s:key name="label">Splunk Forwarder</s:key>
<!-- snip -->
Most of Splunk Enterprise's XML responses relies heavily on namespaces. Wingpy response object can be access as an lxml ElementTree.
license_labes = rsp.xpath(
"/a:feed/a:entry/a:content/s:dict/s:key[@name='label']/text()",
namespaces={
"a": "http://www.w3.org/2005/Atom",
"s": "http://dev.splunk.com/ns/rest",
},
)
print(license_labes)
# ['Splunk Forwarder', 'Splunk Free']
Create a new search and store the Search ID.
rsp = splunk.post("/search/jobs", data={"search": "search host=www1"})
sid = rsp.xpath("/response/sid/text()")[0]
The get_all method evaluates RFC 8288 web linking headers indicating that the client should wait for result processing. Wingpy handles this automatically in the background and finally returns a list of result lxml Elements.
results = splunk.get_all(
"/search/v2/jobs/{search_id}/results",
path_params={"search_id": sid}
)
print(len(results))
Response manipulation - Filtering and JSON¶
In the Splunk Enterprise documentation you can find query paramaters that are allowed multiple times, for instance the f (field) parameter when retrieving search results.
Specify it as a Python list to include multiple values.
rsp = splunk.get_all(
"/search/v2/jobs/{search_id}/results",
path_params={"search_id": sid},
params={"f": ["_time", "source", "host"]},
)
The Splunk Enterprise API can also convert some responses to other formats such as JSON by including the query paramter output_format.
rsp = splunk.get_all("/licenser/licenses", params={"output_mode": "json"})
for license in rsp:
print(license["content"]["label"])
Note
Not all API endpoints support all formats, so check with the official documentation.