Cisco Secure Access Internal Networks sample script

Internal Networks API Guide

This guide provides Python client samples for the Cisco Secure Access Internal Networks API.

Note: Your Secure Access API key must have the permissions to read and write on the deployments.internalnetworks 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 json
import os
from dotenv import load_dotenv

from cisco.secure_access import API
from cisco.secure_access import deployments
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 token_url
from cisco.secure_access import client_id
from cisco.secure_access import client_secret

# Internal Networks API endpoints
internal_networks_endpoint = "internalnetworks"
internal_networks_details_endpoint = "internalnetworks/{}"

load_dotenv()

def get_internal_networks(api):
    ''' Get Internal Networks. '''
    try:
        # Get Internal Networks in the organization
        response = api.Query(deployments, internal_networks_endpoint, GET)

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

def create_internal_network(api, name, ipAddress, prefixLength, site_id=None, tunnel_id=None, network_id=None):
    ''' Create an Internal Network. '''
    try:
        if name is None or ipAddress is None or prefixLength is None:
            raise ValueError("name, ipAddress, and prefixLength are required to update the Internal Network.")

        # Prepare the payload
        payload = {
            "name": name,
            "ipAddress": ipAddress,
            "prefixLength": prefixLength
        }
        if site_id:
            payload['siteId'] = site_id
        elif tunnel_id:
            payload['tunnelId'] = tunnel_id
        elif network_id:
            payload['networkId'] = network_id

        # Create an Internal Network
        response = api.Query(deployments, internal_networks_endpoint, POST, payload)

        # Check the response status
        if response.status_code == 200:
            print(f"Success. POST {internal_networks_endpoint}, {response.json()}")
            return response.json()
        else:
            print(f"Failed to create the Internal Network {name}. Status code: {response.status_code}, Response: {response.text}.")
            return None
    except Exception as e:
        print(f"An error occurred: {e}.")

def get_internal_network(api, origin_id):
    ''' Get the properties of the Internal Network. '''
    try:
        if origin_id is None:
            raise ValueError("internalNetworkId is required to get the Internal Network.")
        url = internal_networks_details_endpoint.format(origin_id)

        # Get the properties for the Internal Network
        response = api.Query(deployments, url, GET)

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

def put_internal_network(api, origin_id, name, ipAddress, prefixLength, site_id=None, tunnel_id=None, network_id=None):
    ''' Update the properties of the Internal Network. '''
    try:
        if origin_id is None or name is None or ipAddress is None or prefixLength is None:
            raise ValueError("origin_id, name, ipAddress, and prefixLength are required to update the Internal Network.")

        # Prepare the payload
        payload = {
            "name": name,
            "ipAddress": ipAddress,
            "prefixLength": prefixLength
        }
        if site_id:
            payload['siteId'] = site_id
        elif tunnel_id:
            payload['tunnelId'] = tunnel_id
        elif network_id:
            payload['networkId'] = network_id

        url = internal_networks_details_endpoint.format(origin_id)

        # Update the properties for the Internal Network
        response = api.Query(deployments, url, PUT, payload)

        # Check if the API request was successful
        if response.status_code == 200:
            print(f"Success. PUT {url}, {response.json()}.")
            return response.json()
        else:
            print(f"Failed to update the Internal Network {origin_id}. Status code: {response.status_code}, Response: {response.text}.")
            return
    except Exception as e:
        print(f"An error occurred: {e}.")

def delete_internal_network(api, origin_id):
    ''' Delete the Internal Network. '''
    try:
        if origin_id is None:
            raise ValueError("origin_id is required to delete the Internal Network.")
        url = internal_networks_details_endpoint.format(origin_id)

        # Delete the Internal Network
        response = api.Query(deployments, url, DELETE)

        # Check if the API request was successful
        if response.status_code == 204:
            print(f"No Content. DELETE {url}.")
        else:
            print(f"Failed to delete the Internal Network {origin_id}. Status code: {response.status_code}, Response: {response.text}.")
    except Exception 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 internal networks in the organization
        json_data = get_internal_networks(api)

        # create an internal network
        name = "internal network one"
        ipAddress = "198.2.2.8"
        prefixLength = 32
        site_id = 6355544 # Specify one of: siteId, tunnelId, or networkId
        json_data = create_internal_network(api, name, ipAddress, prefixLength, site_id)
        origin_id = None

        # get an internal network using the originId
        if 'originId' in json_data:
            origin_id = json_data['originId']
        json_data = get_internal_network(api, origin_id)

        # update an internal network
        name = 'internal network two'
        ipAddress = '198.2.2.8'
        prefixLength = 32
        site_id = 6614148 # Specify one of: siteId, tunnelId, or networkId
        json_data = put_internal_network(api, origin_id, name, ipAddress, prefixLength, site_id)

        # delete an internal network
        json_data = delete_internal_network(api, origin_id)

    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()