Python REST API

In the Python programming language, you can script a client application that interacts with REST APIs including that of IBM Spectrum Protect Plus. The examples in this section and throughout this guide use third-party library Requests for HTTP transactions.

Applicable Python releases: The provided examples are based on the following releases: Python series: Python 3.5, 3.6, 3.7, and 3.8.

Getting a session ID using Python

Assume that you want to work with IBM Spectrum Protect Plus virtual with the following configuration:

  • IPv4 Address: 10.0.0.100

  • Username: Sarah

  • Password: MyPassw0rd!

  • SSL verification: False, ignore warnings.

The following Python script loads libraries and values to access to the REST API.

import json
import requests

spp_ipv4 = '10.0.0.100'
spp_username = 'Sarah'
spp_password = 'MyPassw0rd!'
spp_verify = False              # Disable SSL.

# Supress HTTPS warnings when spp_verify is set to False.
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

The previous script is followee by this Python snippet. It retrieves a session ID from the target IBM Spectrum Protect Plus application.

spp_session = requests.post('https://' + spp_ipv4 + '/api/endeavour/session',
    auth=(spp_username, spp_password),
    headers={
        'Accept':       'application/json',
        'Content-type': 'application/json'
    },
    verify=spp_verify
)

spp_session = json.loads(spp_session.text)    # Convert to JSON
spp_sessionid = spp_session['sessionid']

print(spp_sessionid)
ee88d182812f49c98bbf9c819d69af07

You will use this session ID for further operations. For more information about the sessionIDs, see Creating a session ID.

Sending a request to the REST API by using Python

Assume that you append the following Python snippet to the previous script. The snippet sends an HTTP request to the REST API and starts an inventory job for virtualized systems, such as virtual machines hosted on vCenter Server. For more information about this operation, see Running an inventory job for virtualized systems.

_params = {
    "action":    "start",
    "actionname": "start"
}

_data = ""

requests.post('https://' + spp_ipv4 + '/api/endeavour/job/1004,
    headers={
        'Accept':                'application/json',
        'Content-type':          'application/json',
        'X-Endeavour-Sessionid': spp_sessionid
    },
    params=_params, data=_data, verify=spp_verify
)

The structure of this POST command is similar to the command for getting a session ID except for the URI and the session ID in the header.

Because the REST API has a consistent syntax, you can use similar request commands for various purposes. You can enhance those basic structures with many other methods and mechanisms that are available in Python and its third-party libraries.