Why Python requests
Python's requests library is the standard way to call REST APIs from Python. It's not part of the standard library, but it's so widely used it might as well be. The API is clean, the error handling is straightforward, and it handles the HTTP details so you don't have to.
For network automation, it's the right tool for scripting RESTCONF calls, calling vendor management APIs, and querying any HTTP-based service. Once you know requests, you can automate almost any network device or platform that exposes an API.
Installing and Importing
pip install requestsAt the top of your script:
import requests
import json
import urllib3 # Suppress SSL warnings for lab use (use proper certs in production)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)The urllib3 warning suppression is for lab environments where you're hitting devices with self-signed certs. In production, set verify='/path/to/ca-bundle.pem' instead of verify=False.
Your First GET Call
BASE_URL = "https://sandbox-iosxe-latest-1.cisco.com"
AUTH = ("admin", "C1sco12345")
HEADERS = { "Accept": "application/yang-data+json", "Content-Type": "application/yang-data+json"
} response = requests.get( f"{BASE_URL}/restconf/data/ietf-interfaces:interfaces", auth=AUTH, headers=HEADERS, verify=False
) print(response.status_code)
print(response.json())That's it. The response object contains everything: status code, headers, and body. response.json() parses the JSON body into a Python dict automatically.
The Response Object
Every requests call returns a Response object with these attributes you'll use constantly:
response.status_code: The HTTP status code (200, 204, 404, etc.)response.json(): Parses the body as JSON and returns a dict/listresponse.text: The raw response body as a stringresponse.headers: Response headers as a dictresponse.ok: True if status code is below 400
Handling Errors
Don't assume a request succeeded. Always check:
response = requests.get(url, auth=AUTH, headers=HEADERS, verify=False) if not response.ok: print(f"Error {response.status_code}: {response.text}") exit(1)Or use raise_for_status() which raises an exception on 4xx and 5xx responses:
try: response.raise_for_status()
except requests.exceptions.HTTPError as e: print(f"HTTP error: {e}") exit(1)Parsing the JSON Response
The RESTCONF interface list comes back nested. Here's how to navigate it:
data = response.json()
interfaces = data["ietf-interfaces:interfaces"]["interface"] for iface in interfaces: name = iface["name"] enabled = iface.get("enabled", False) description = iface.get("description", "") print(f"{name}: {'UP' if enabled else 'DOWN'} , {description}")Use .get() for fields that might not be present (like description). It returns None (or your default) instead of raising a KeyError.
Getting One Interface
iface_name = "GigabitEthernet1"
url = f"{BASE_URL}/restconf/data/ietf-interfaces:interfaces/interface={iface_name}" response = requests.get(url, auth=AUTH, headers=HEADERS, verify=False) if response.status_code == 404: print(f"Interface {iface_name} not found")
elif response.ok: iface = response.json()["ietf-interfaces:interface"] print(json.dumps(iface, indent=2))A Complete Config Backup Script
Here's a 30-line script that backs up all interface descriptions to a JSON file:
import requests
import json
import urllib3
from datetime import datetime urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) BASE_URL = "https://sandbox-iosxe-latest-1.cisco.com"
AUTH = ("admin", "C1sco12345")
HEADERS = {"Accept": "application/yang-data+json"} def get_interfaces(): url = f"{BASE_URL}/restconf/data/ietf-interfaces:interfaces" r = requests.get(url, auth=AUTH, headers=HEADERS, verify=False) r.raise_for_status() return r.json()["ietf-interfaces:interfaces"]["interface"] def backup_descriptions(interfaces): backup = {} for iface in interfaces: backup[iface["name"]] = { "description": iface.get("description", ""), "enabled": iface.get("enabled", True) } return backup interfaces = get_interfaces()
backup = backup_descriptions(interfaces) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"interface_backup_{timestamp}.json" with open(filename, "w") as f: json.dump(backup, f, indent=2) print(f"Backed up {len(backup)} interfaces to {filename}")SSL Verification in Production
In production, don't use verify=False. If your device uses a self-signed cert, download the cert and pass the path: verify='/etc/ssl/certs/device-ca.pem'. If it uses a cert from a corporate CA, point at the CA bundle. The verify=False approach works for lab but leaves you open to man-in-the-middle attacks on a real network.
Practical Takeaway
The pattern is always the same: build the URL, set auth and headers, call requests.get(), check the status, parse the JSON. Once that loop is in your muscle memory, automation becomes the easy part and knowing the YANG paths becomes the actual work.
Watch the video
This is part of the Network Automation 101 series on YouTube.
Next in this series
Automate Cisco Config with Python requests: RESTCONF End to End →
Comments (0)
Please sign in to comment.