Cisco Secure Access Service Objects API samples overview

Service Objects API Guide

This guide provides Python client samples for the Cisco Secure Access Service Objects API.

Note: Your Secure Access API key must have the permissions to read and write on the policies key scope. For more information about the API key scopes, see Secure Access OAuth 2.0 Scopes.

First get your Secure Access API key, set up your environment, and install the Secure Access API client. For more information, see Samples Overview.

Run the Script

  1. Copy the script to a local file called main.py. Locate the script in your environment in a directory above the cisco directory.
  2. Run python3 main.py.

main.py

"""
Copyright (c) 2025 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at

https://developer.cisco.com/docs/licenses

All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""

import requests
from requests_toolbelt import MultipartEncoder
import pandas as pd
import json
import os
from dotenv import load_dotenv
from io import StringIO
import matplotlib.pyplot as plt

from cisco.secure_access import API
from cisco.secure_access import policies
from cisco.secure_access import GET
from cisco.secure_access import POST
from cisco.secure_access import PUT
from cisco.secure_access import DELETE
from cisco.secure_access import POST_MULTIPART_FORM_DATA
from cisco.secure_access import token_url
from cisco.secure_access import client_id
from cisco.secure_access import client_secret

# Service Objects API endpoints
service_objects_endpoint = "objects/serviceObjects"
service_object_details_endpoint = "objects/serviceObjects/{}"
service_objects_references_endpoint = "objects/serviceObjects/references"
service_object_references_detail_endpoint = "objects/serviceObjects/{}/references"

load_dotenv()

def get_service_objects(api):
    ''' Get the Service Objects in the organization. '''
    try:
        # Get the Service Objects in the organization
        response = api.Query(policies, service_objects_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. GET {service_objects_endpoint}, {response.json()}")
        else:
            print(f"Failed to get the service objects. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def post_service_object(api, name=None, value=None, description=None):
    ''' Create a Service Object in the organization. '''
    try:
        if name is None or value is None:
            raise ValueError("Name and Value are required to create the service object.")

        # Prepare the payload
        payload = {
            "name": name,
            "value": value,
            "description": description
        }

        # Create a Service Object
        response = api.Query(policies, service_objects_endpoint, POST, payload)

        # Check the response status
        if response.status_code == 201:
            print(f"Success: POST {service_objects_endpoint}, {response.json()}.")
            return response.json()['id']
        else:
            print(f"Failed to create the service object: {response.json()['name']}. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_service_object_details(api, id):
    ''' Get the properties for a Service Object. '''
    try:
        url = service_object_details_endpoint.format(id)
        
        # Get a Service Object
        response = api.Query(policies, url, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success: GET {url}, {response.json()}.")
        else:
            print(f"Failed to get a service object. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def put_service_object_details(api, id, name=None, value=None, description=None):
    ''' Update the properties of a Service Object. '''
    try:
        url = service_object_details_endpoint.format(id)
        if name is None or value is None:
            raise ValueError("Name and Value are required to update the service object.")

        # Prepare the payload.
        payload = {
            "name": name,
            "value": value,
            "description": description
        }
        # Update the properties of a Service Object
        response = api.Query(policies, url, PUT, payload)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success: PUT {url}, {response.json()}.")
        else:
            print(f"Failed to get service object. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def delete_service_object(api, id):
    ''' Delete the Service Object. '''
    try:
        url = service_object_details_endpoint.format(id)
        
        # Delete the Service Object
        response = api.Query(policies, url, DELETE)

        # Check if the API request was successful
        if response.status_code == 204:
            print(f"Deleted Service Object with ID: {id}.")
        else:
            print(f"Failed to get service object. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def get_service_objects_references(api):
    ''' Get the objects that refer to the service objects. '''
    try:
        # Get the references to the Service Objects
        response = api.Query(policies, service_objects_references_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success: GET {service_objects_references_endpoint}, {response.json()}.")
        else:
            print(f"Failed to get references to service objects. Status code: {response.status_code}, Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def get_service_object_references_detail(api, id):
    ''' Get the references for a specific service object. '''

    try:
        # Get the references for a Service Object
        url = service_object_references_detail_endpoint.format(id)
        response = api.Query(policies, url, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success: GET {url}, {response.json()}.")
        else:
            print(f"Failed to get references for the Service Object {id}. Status code: {response.status_code}, Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def main():
    # Exit out if the required client_id or client_secret is not set
    for var in ['API_KEY', 'API_SECRET', 'OUTPUT_DIR']:
        if os.environ.get(var) == None:
            print("Required environment variable: {} not set".format(var))
            exit()

    # Get an API token
    api = API(token_url, client_id, client_secret)

    try:

        # Get the service objects
        get_service_objects(api)

        # Create a service object
        name= "One Service Object"
        value = {
            "ports": ["6500-8900"],
            "protocol": "tcp"
        }
        description = f"description for Service Object {name}"
        id = post_service_object(api, name, value, description)

        # Get the details for a service object
        get_service_object_details(api, id)

        # Update a service object
        updated_name = f"{name} with updates"
        value = {
            "ports": ["8100"],
            "protocol": "udp"
        }
        description = f"{name} with updates"
        update_service_object_details(api, id, updated_name, value, description)

        # Get the references to the service objects
        get_service_objects_references(api)

        # Get the details for the references to the service objects
        get_service_object_references_detail(api, id)

        # Delete a service object using the service objects' ID.
        delete_service_object(api, id)

    except Exception as e:
        print(e)

# main
if __name__ == "__main__":
    main()

get_service_objects_and_graph

Secure Access SSO login
def get_service_objects_and_graph(api):
    ''' Get the Service Objects in the organization and plot the counts of the types of protocols. '''

    try:
        print(f"Get the service objects in the organization.")
        response = api.Query(policies, service_objects_endpoint, GET)

        # Check if the API request was successful
        if response.status_code == 200:
            service_objects = response.json()['results']
            df = pd.json_normalize(service_objects)
            df.to_csv(service_objects_csv_file, mode='w')
            new_df = df[['name', 'description', 'value.protocol', 'value.ports']]
            new_df_counts = df['value.type'].value_counts()
            tcp_val = new_df_counts['tcp'] if 'tcp' in new_df_counts else 0
            udp_val = new_df_counts['udp'] if 'udp' in new_df_counts else 0
            icmp_val = new_df_counts['icmp'] if 'icmp' in new_df_counts else 0
            any_val = new_df_counts['any'] if 'any' in new_df_counts else 0
            df_to_plot = pd.DataFrame({'Service protocol types': ['tcp', 'udp', 'icmp', 'any'], 'counts': [tcp_val, udp_val, icmp_val, any_val]})
            df_to_plot.plot.bar(x='Service Object types', y='counts', rot=0)
        else:
            print(f"Failed to get the Service Objects. Status code: {response.status_code}, Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")