How to use REST API

The following sample program written in Python can do the following:
  • Access the token with the provided MI username and password.
  • Get the online OpenAPI document.
  • Get the data of clusters endpoint.

Sample Python script

To use this script:
  • Update ts7700Url to the target TS7700.
  • Update authData to match the valid Management Interface user ID and password on the target TS7700.
  • If the endpoint data is other than clusters, serviceUrl needs to be changed, as well as OpenLiberty document JSON keys.
import requests
import json
import yaml
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)


# TS7700 URL to set
ts7700Url = 'https://popcorn.tuc.stglabs.ibm.com'
# Authentication data to set
authData = {'username':'admin','password':'passw0rd'}

# Global variables used internally
# V1 endpoint
tokenEndpoint = '/api/v1/'
# Doc endpoint
docEndpoint = '/api/docs'
# Token
token = ''
# OpenLiberty document
docData = {}
# Authorization header
authHeader = {}


def postToken():
    """
    POST to retrieve token from authData. Always need to be called first.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """       
    # Convert authentication data to JSON
    authDataJson = json.dumps(authData)
    # Create target endpoint URL
    tokenUrl = ts7700Url + tokenEndpoint + 'token'
    # POST to get token
    try:
        response = requests.post(tokenUrl, data=authDataJson, verify=False)
        # Retrieve token when HTTP RC = 200
        if response.status_code == 200:
            # Get json output
            jsonData = response.json()
            # Make token global and fill it
            global token
            token=jsonData['data'][0]['token']
        else:
            print("Failed to get token with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get token: ", e)
        
    return response.status_code


def getDoc():
    """
    GET OpenLiberty document.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """
    # Create doc endpoint URL
    docUrl = ts7700Url + docEndpoint
    # GET document
    try:
        response = requests.get(docUrl, verify=False)
        # Convert YAML output when HTTP RC = 200
        if response.status_code == 200:
            ymlOut = yaml.safe_load(response.text)      # Load yaml output
            jsonOut = json.dumps(ymlOut, default=str)   # Dump yaml output
            # Make docData global and fill it
            global docData
            docData = json.loads(jsonOut)
            
            # Example to get clusters service attributes
            clusters = docData['components']['schemas']['Cluster']['properties']
            # Get all keys
            clustersKeys = list(clusters.keys())
            print(f'clusters keys: {clustersKeys}\n')
            # Get type of state column
            clustersStateType = clusters['state']['type']
            print(f'clusters state type: {clustersStateType}\n')
            # Get description of id column
            #clustersIdDesc = clusters['id']['description']
            #print(f'clusters id desc: {clustersIdDesc}')
            # Get enum values of state column
            clustersStateEnums = clusters['state']['enum']
            print(f'type enums: {clustersStateEnums}\n')
        else:
            print("Failed to get doc with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get doc: ", e)

    return response.status_code
        
    
def getClustersService():
    """
    GET clusters service.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """
    # Set header information with token
    auth = 'Bearer ' + token
    # Make authHeader global and fill it
    global authHeader
    authHeader = {'Authorization': auth}    
    # Create service endpoint URL
    serviceUrl = ts7700Url + tokenEndpoint + 'clusters'
    # GET clusters service
    try:
        response = requests.get(serviceUrl, headers=authHeader, verify=False)
        # Parse  when HTTP RC = 200
        if response.status_code == 200 or response.status_code == 206:
            jsonData = response.json()
            
            # Example to check each cluster's state
            clusterCount = jsonData['metadata']['resources']
            clustersData = jsonData['data']
            stateEnums = docData['components']['schemas']['Cluster']['properties']['state']['enum']
            for i in range(clusterCount):
                clusterId = clustersData[i]['id']
                clusterState = clustersData[i]['state']
                if clusterState not in stateEnums:
                    print(f'cluster {clusterId} state is unknown state: {clusterState}')
                elif clusterState != 'ONLINE':
                    print(f'cluster {clusterId} state is not healthy state: {clusterState}')
                else:
                    print(f'cluster {clusterId} state is online and healthy')
        else:
            print("Failed to get clusters service with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get clusters service: ", e)

    return response.status_code


def main():
    # POST to retrieve token
    httpRC = postToken()
    
    # GET OpenLiberty document
    if httpRC == 200:
        httpRC = getDoc()
        
    # GET clusters service
    if httpRC == 200:
        httpRC = getClustersService()
        

if __name__ == "__main__":
    main()
The script is updated to apply the new versioning design since the code level of 8.60.0.x.
  • Update endpointVersion for the target endpoint. The generation version (tokenEndpoint) is always set to v2.
import requests
import json
import yaml
import urllib3
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)


# TS7700 URL to set
ts7700Url = 'https://pine.tuc.stglabs.ibm.com'
# Authentication data to set
authData = {'username':'admin','password':'passw0rd'}

# Global variables used internally
# V2 generation endpoint
tokenEndpoint = '/api/v2/'
# Endpoint version (new at 8.60.0.x or above)
endpointVersion = '6.0'
# Doc endpoint
docEndpoint = '/api/docs'
# Token
token = ''
# OpenLiberty document
docData = {}
# Authorization header
authHeader = {}


def postToken():
    """
    POST to retrieve token from authData. Always need to be called first.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """       
    # Convert authentication data to JSON
    authDataJson = json.dumps(authData)
    # Create target endpoint URL
    tokenUrl = ts7700Url + tokenEndpoint + 'token'
    # POST to get token
    try:
        response = requests.post(tokenUrl, data=authDataJson, verify=False)
        # Retrieve token when HTTP RC = 200
        if response.status_code == 200:
            # Get json output
            jsonData = response.json()
            # Make token global and fill it
            global token
            token=jsonData['data'][0]['token']
        else:
            print("Failed to get token with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get token: ", e)
        
    return response.status_code


def getDoc():
    """
    GET OpenLiberty document.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """
    # Create doc endpoint URL
    docUrl = ts7700Url + docEndpoint
    # GET document
    try:
        response = requests.get(docUrl, verify=False)
        # Convert YAML output when HTTP RC = 200
        if response.status_code == 200:
            ymlOut = yaml.safe_load(response.text)      # Load yaml output
            jsonOut = json.dumps(ymlOut, default=str)   # Dump yaml output
            # Make docData global and fill it
            global docData
            docData = json.loads(jsonOut)
            
            # Example to get clusters service attributes
            clusters = docData['components']['schemas']['Cluster']['properties']
            # Get all keys
            clustersKeys = list(clusters.keys())
            print(f'clusters keys: {clustersKeys}\n')
            # Get type of state column
            clustersStateType = clusters['state']['type']
            print(f'clusters state type: {clustersStateType}\n')
            # Get description of id column
            #clustersIdDesc = clusters['id']['description']
            #print(f'clusters id desc: {clustersIdDesc}')
            # Get enum values of state column
            clustersStateEnums = clusters['state']['enum']
            print(f'type enums: {clustersStateEnums}\n')
        else:
            print("Failed to get doc with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get doc: ", e)

    return response.status_code
        
    
def getClustersService():
    """
    GET clusters service.

    Parameters
    ----------
    None

    Returns
    -------
    HTTP RC
    """
    # Set header information with token
    auth = 'Bearer ' + token
    # Make authHeader global and fill it
    global authHeader
    authHeader = {'Authorization': auth, 'API-Version': endpointVersion}    
    # Create service endpoint URL
    serviceUrl = ts7700Url + tokenEndpoint + 'clusters'
    # GET clusters service
    try:
        response = requests.get(serviceUrl, headers=authHeader, verify=False)
        # Parse  when HTTP RC = 200
        if response.status_code == 200 or response.status_code == 206:
            jsonData = response.json()
            
            # Example to check each cluster's state
            clusterCount = jsonData['metadata']['resources']
            clustersData = jsonData['data']
            stateEnums = docData['components']['schemas']['Cluster']['properties']['state']['enum']
            for i in range(clusterCount):
                clusterId = clustersData[i]['id']
                clusterState = clustersData[i]['state']
                if clusterState not in stateEnums:
                    print(f'cluster {clusterId} state is unknown state: {clusterState}')
                elif clusterState != 'online':
                    print(f'cluster {clusterId} state is not healthy state: {clusterState}')
                else:
                    print(f'cluster {clusterId} state is online and healthy')
        else:
            print("Failed to get clusters service with HTTP RC {response.status_code}. Exit")
    except requests.exceptions.RequestException as e:
        # Error case
        print("Failed to get clusters service: ", e)

    return response.status_code


def main():
    # POST to retrieve token
    httpRC = postToken()
    
    # GET OpenLiberty document
    if httpRC == 200:
        httpRC = getDoc()
        
    # GET clusters service
    if httpRC == 200:
        httpRC = getClustersService()
        

if __name__ == "__main__":
    main()

Response

clusters keys: ['id', 'distributedLibrarySeqNum', 'name', 'description', 'clusterFamily', 'sn', 'mtm', 'product', 'microcodeLevel', 'state', 'varyDevicesOnlineRequired', 'fenced', 'licensedVirtualDrives', 'installedCapacity', 'licensedCapacity', 'usedCapacity', 'licensedThroughput', 'licensedPremigrationQueueSize', 'objectEnabled', 'physicalTapeEnabled', 'cloudEnabled', 'gridEnabled']

clusters state type: string

type enums: ['preparingForService', 'inService', 'inaccessible', 'critical', 'error', 'impact', 'warning', 'online']

cluster 7 state is not healthy state: error