Cisco Secure Access Network Objects API samples overview

Network Objects API Guide

This guide provides Python client samples for the Cisco Secure Access Network 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

# Network Objects API endpoints
network_objects_endpoint = "objects/networkObjects"
network_object_details_endpoint = "objects/networkObjects/{}"
network_objects_references_endpoint = "objects/networkObjects/references"
network_object_references_details_endpoint = "objects/networkObjects/{}/references"

load_dotenv()

def get_network_objects(api):
    ''' Get the Network Objects. '''
    try:
        # Get Network Objects in the organization
        response = api.Query(policies, network_objects_endpoint, GET)

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

def post_network_object(api, name=None, value=None, description=None):
    ''' Create a Network Object. '''
    try:
        if name is None or value is None:
            raise ValueError("Name and Value are required to update the network object.")

        # Prepare the payload
        payload = {
            "name": name,
            "value": value,
            "description": description
        }
        # Create a Network Object
        response = api.Query(policies, network_objects_endpoint, POST, payload)

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

def get_network_object_details(api, id):
    ''' Get the properties for a Network Object. '''
    try:
        url = network_object_details_endpoint.format(id)

        # Get the properties for a Network 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 the network object {id}. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

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

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

        # Update the properties of a Network 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: {response.json()}.")
        else:
            print(f"Failed to update the network object {id}. Status code: {response.status_code}, Response: {response.text}.")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")

def delete_network_object_details(api, id):
    ''' Delete the Network Object. '''
    try:
        url = network_object_details_endpoint.format(id)

        # Delete the Network Object
        response = api.Query(policies, url, DELETE)

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

def get_network_objects_references(api):
    ''' Get the refererences for the Network Objects. '''
    try:
        # Get the references for the Network Objects
        response = api.Query(policies, network_objects_references_endpoint, GET)

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

def get_network_object_references_details(api, id):
    ''' Get the references for a specific Network Object. '''
    try:
        url = network_object_references_details_endpoint.format(id)
        # Get the references for the Network 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 the references for the network 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 network objects for the organization.
        get_network_objects(api)

        # Create a network object
        name = "Network Object One"
        description = f"description for {name}"
        value = {
            "addresses": ['192.68.1.0/24'],
            "type": "network"
        }
        id = post_network_object(api, name, value, description)

        # Get the details for a network object
        get_network_object_details(api, id)

        # Update a network object
        name = f"{name} with updates"
        value = {
            "addresses": ['192.168.10.0/0.0.0.255'],
            "type": "network"
        }
        description = f"updated description for {name}"

        update_network_object_details(api, id, name, value, description)

        # Get the references to the Network Objects
        get_network_objects_references(api)

        # Get the details for the references to the Network Objects
        get_network_object_references_details(api, id)

        # Delete a network object using the network objects' ID.
        delete_network_object_details(api, id)

    except Exception as e:
        print(e)

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

get_network_objects_and_graph

Secure Access SSO login
def get_network_objects_and_graph(api):
    ''' Get the Network Objects in the organization and plot the counts of each network type. '''

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

        # Check if the API request was successful
        if response.status_code == 200:
            network_objects = response.json()['results']
            df = pd.json_normalize(network_objects)
            df.to_csv(network_objects_csv_file, mode='w')
            new_df = df[['name', 'description', 'value.type', 'value.addresses']]
            new_df_counts = df['value.type'].value_counts()
            fqdn_val = new_df_counts['fqdn'] if 'fqdn' in new_df_counts else 0
            network_val = new_df_counts['network'] if 'network' in new_df_counts else 0
            range_val = new_df_counts['range'] if 'range' in new_df_counts else 0
            host_val = new_df_counts['host'] if 'host' in new_df_counts else 0

            df_to_plot = pd.DataFrame({'Network object types': ['network', 'range', 'host', 'fqdn'], 'counts': [network_val, range_val, host_val, fqdn_val]})
            df_to_plot.plot.bar(x='Network Object types', y='counts', rot=0)
        else:
            print(f"Failed to get the network objects. Status code: {response.status_code}, Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}.")