Secure Web Gateway Device Settings API Guide
This guide provides Python client samples for the Cisco Secure Access Secure Web Gateway (SWG) Device Settings API.
Note: Your Secure Access API key must have the permissions to read and write on the deployments
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
- Copy the script to a local file called
main.py
. Locate the script in your environment in a directory above thecisco
directory. - 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.
"""
from datetime import datetime
import pandas as pd
import requests
import json
import os
from dotenv import load_dotenv
from cisco.secure_access import write_to_csv
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 token_url
from cisco.secure_access import client_id
from cisco.secure_access import client_secret
# Roaming Computers API endpoints
roaming_computers_endpoint = "roamingcomputers"
# SWG Device Settings API endpoints
list_swg_device_settings_endpoint = "deviceSettings/SWGEnabled/list"
set_swg_device_settings_endpoint = "deviceSettings/SWGEnabled/set"
remove_swg_device_settings_endpoint = "deviceSettings/SWGEnabled/remove"
# The directory where to write out files
output_dir = os.environ.get('OUTPUT_DIR') or os.get_env['OUTPUT_DIR']
# sample csv file
roaming_computers_csv_file = output_dir + "/roaming-computers.csv"
load_dotenv()
def get_all_roaming_computers(api, csv_file=None):
''' Get Roaming Computers. '''
try:
hasMore = True
page = 1
while hasMore:
url = roaming_computers_endpoint + "?page=" + str(page)
# Get Roaming Computers in the organization
response = api.Query(deployments, url, GET)
# Check if the API request was successful
if response.status_code == 200:
if len(response.json()) > 0:
df = pd.json_normalize(response.json())
write_to_csv(df, csv_file)
page += 1
else:
hasMore = False
else:
print(f"Failed to get the Roaming Computers. Status code: {response.status_code}, Response: {response.text}.")
hasMore = False
return df['originId'].to_list() if page > 1 else None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}.")
def list_swg_device_settings(api, originIds=None):
''' Get the SWG device settings for the roaming computers. '''
try:
if originIds is None:
raise ValueError("The list of origin ID is required to list the SWG device settings.")
payload = {
"originIds": originIds
}
# Update the SWG device settings on the roaming computers
response = api.Query(deployments, list_swg_device_settings_endpoint, POST, payload)
# Check the response status
if response.status_code == 200:
print(f"Success. POST {list_swg_device_settings_endpoint}, {response.json()}")
return response.json()
else:
print(f"Failed to list the SWG device settings for the Roaming Computers. Status code: {response.status_code}, Response: {response.text}.")
return None
except Exception as e:
print(f"An error occurred: {e}.")
def remove_swg_device_settings(api, originIds=None):
''' Remove the SWG device settings for the roaming computers. '''
try:
if originIds is None:
raise ValueError("The list of origin ID is required to remove the SWG device settings.")
payload = {
"originIds": originIds
}
# Remove the SWG device settings on the roaming computers
response = api.Query(deployments, remove_swg_device_settings_endpoint, POST, payload)
# Check if the API request was successful
if response.status_code == 200:
print(f"No Content. POST {remove_swg_device_settings_endpoint}")
return None
else:
print(f"Failed to remove the SWG device settings for the roaming computers. Status code: {response.status_code}, Response: {response.text}.")
return None
except Exception as e:
print(f"An error occurred: {e}.")
def set_swg_device_settings(api, originIds=None, value=None):
''' Update the SWG device settings for the roaming computers. '''
try:
if originIds is None or value is None:
raise ValueError("The list of origin ID and value is required to set the SWG device settings.")
payload = {
"originIds": originIds,
"value": value
}
# Set the SWG device settings on the roaming computers
response = api.Query(deployments, set_swg_device_settings_endpoint, POST, payload)
# Check if the API request was successful
if response.status_code == 200:
print(f"Success. POST {set_swg_device_settings_endpoint}, {response.json()}")
return response.json()
else:
print(f"Failed to set the SWG device settings for the roaming computers. Status code: {response.status_code}, Response: {response.text}.")
return None
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:
# Use pagination to get all roaming computers in the organization
originIds = get_all_roaming_computers(api, roaming_computers_csv_file)
if originIds and len(originIds) > 0:
print(f"Origin Ids are: {originIds}")
# list the swg device settings for the roaming computers
json_data = list_swg_device_settings(api, originIds)
# update the swg device settings for the roaming computers
value='1'
json_data = set_swg_device_settings(api, originIds, value)
# remove the swg device settings for the roaming computers
json_data = remove_swg_device_settings(api, originIds)
# Set and then check the device settings again
json_data = set_swg_device_settings(api, originIds, value)
json_data = list_swg_device_settings(api, originIds)
except Exception as e:
print(e)
if __name__ == "__main__":
main()