HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 10 of 20 — Python for Network Engineers
intermediate Chapter 10 of 20

REST APIs in Python — Automating Network Controllers & Platforms

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

REST API Fundamentals — HTTP Methods, Status Codes & JSON

Representational State Transfer (REST) APIs are the backbone of network automation, enabling communication between network controllers, platforms, and automation scripts. Understanding the foundational principles of REST APIs is critical for network engineers aiming to leverage REST API Python network automation techniques effectively.

At its core, REST utilizes HTTP protocols to perform operations on network devices and management platforms. The primary HTTP methods include:

  • GET: Retrieve data from a server, such as device information or network status.
  • POST: Create new resources or initiate actions, like provisioning a new device or configuring a policy.
  • PUT: Update existing resources, such as modifying device configurations.
  • DELETE: Remove resources, like deleting an outdated device entry.

Each HTTP request receives a status code that indicates the outcome:

Status Code Description
200 OK Successful request, response contains the requested data.
201 Created Resource successfully created, typically in response to POST.
204 No Content Request succeeded but no content to return, often for DELETE operations.
400 Bad Request Malformed request or invalid parameters.
401 Unauthorized Authentication required or failed.
404 Not Found Requested resource does not exist.
500 Internal Server Error Server encountered an unexpected condition.

Communication with network APIs commonly employs JSON (JavaScript Object Notation) for data exchange due to its lightweight and human-readable format. JSON structures data into key-value pairs, making it ideal for transmitting device configurations, status reports, and command responses.

For example, retrieving device inventory from a network controller might return a JSON payload like:

{
  "devices": [
    {"id": "1", "name": "Switch-1", "status": "active"},
    {"id": "2", "name": "Router-3", "status": "inactive"}
  ]
}

Understanding these core concepts ensures that network engineers can craft robust scripts to automate network management tasks efficiently using Python.

Python requests Library — GET, POST, PUT, DELETE & Headers

The Python requests library is fundamental for implementing REST API Python network automation. It simplifies sending HTTP requests and handling responses, making it an essential tool for network automation scripts.

To perform API interactions, the typical workflow involves:

  1. Constructing the request URL for the specific API endpoint.
  2. Adding necessary headers, such as Content-Type and Authorization tokens.
  3. Sending the request with appropriate method (GET, POST, etc.).
  4. Processing the response, checking status codes, and parsing JSON data.

GET Requests

Use requests.get() to retrieve data from network controllers like Cisco DNA Center or Meraki dashboards:

import requests

url = "https:///dna/intent/api/v1/network-device"
headers = {
    "X-Auth-Token": "",
    "Content-Type": "application/json"
}
response = requests.get(url, headers=headers)

if response.status_code == 200:
    devices = response.json()
    print(devices)
else:
    print(f"Failed to retrieve data: {response.status_code}")

POST Requests

Use requests.post() to create or trigger actions, such as deploying configurations:

payload = {
    "name": "New Network",
    "type": "Wireless"
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 201:
    print("Resource created successfully")

PUT Requests

Use requests.put() to update existing resources:

update_payload = {
    "name": "Updated Network Name"
}
response = requests.put(url + "/", headers=headers, json=update_payload)

DELETE Requests

Remove resources with requests.delete():

response = requests.delete(url + "/", headers=headers)
if response.status_code == 204:
    print("Resource deleted successfully")

Custom Headers & Authentication

Headers often include authentication tokens or API keys:

headers = {
    "Authorization": "Bearer ",
    "Content-Type": "application/json"
}

Mastering the requests library enables network engineers to develop flexible scripts that interact seamlessly with various network APIs.

Authentication — API Keys, Tokens & OAuth2 for Network APIs

Secure access to network APIs like Cisco DNA Center or Meraki dashboard requires proper authentication mechanisms. Implementing robust authentication ensures only authorized scripts and users can modify or retrieve network data.

The common authentication methods include:

  • API Keys: Simple tokens passed in headers; suitable for straightforward integrations.
  • Bearer Tokens: Typically used with OAuth2, these tokens are included in the Authorization header as Bearer <token>.
  • OAuth2: A standard protocol for delegated access, providing secure token exchange and refresh capabilities.

API Keys & Tokens

Many network platforms, such as Meraki, generate API keys from their dashboards. These keys are static and should be stored securely, often in environment variables or configuration files.

headers = {
    "X-Cisco-Meraki-API-Key": "",
    "Content-Type": "application/json"
}

OAuth2 Authorization

OAuth2 involves obtaining an access token through an authorization flow, which can then be used in subsequent API calls:

# Example: Get OAuth2 token
import requests

auth_url = "https://auth.server.com/oauth/token"
data = {
    "client_id": "",
    "client_secret": "",
    "grant_type": "client_credentials"
}
response = requests.post(auth_url, data=data)
token = response.json().get("access_token")
headers = {
    "Authorization": f"Bearer {token}"
}

Best Practices for Authentication

  • Never hard-code tokens or API keys directly into scripts; utilize environment variables.
  • Implement token refresh logic for OAuth2 tokens nearing expiration.
  • Use HTTPS to encrypt token exchanges, ensuring security.

Effective authentication management is vital for maintaining secure and reliable network automation workflows, especially when integrating with multiple platforms like Cisco DNA Center and Meraki. For comprehensive training, consider exploring courses at Networkers Home.

Cisco DNA Center API — Device Inventory & Path Trace

Cisco DNA Center provides a comprehensive REST API to manage and monitor network devices, simplify configurations, and troubleshoot issues. Automating interactions with Cisco DNA Center API enhances network visibility and control through REST API Python network automation.

Retrieving Device Inventory

One common task is fetching the list of network devices, which can be achieved via a GET request:

import requests

dna_center_url = "https:///dna/intent/api/v1/network-device"
headers = {
    "X-Auth-Token": "",
    "Content-Type": "application/json"
}
response = requests.get(dna_center_url, headers=headers)

if response.status_code == 200:
    devices = response.json().get("response", [])
    for device in devices:
        print(f"Device Name: {device['hostname']}, IP: {device['managementIpAddress']}, Type: {device['type']}")
else:
    print(f"Failed to fetch devices: {response.status_code}")

Path Trace for Troubleshooting

Path trace allows network engineers to identify the route taken by packets through the network, aiding in troubleshooting latency or connectivity issues.

path_trace_url = "https:///dna/intent/api/v1/client-health"
payload = {
    "macAddress": "",
    "timestamp": 0
}
response = requests.post(path_trace_url, headers=headers, json=payload)

if response.status_code == 202:
    task_id = response.json()['response']['taskId']
    # Poll for status
    status_url = f"https:///dna/intent/api/v1/task/{task_id}"
    while True:
        status_resp = requests.get(status_url, headers=headers)
        status = status_resp.json()['response']['status']
        if status == 'SUCCESS':
            print("Path trace completed.")
            break
        elif status == 'FAILURE':
            print("Path trace failed.")
            break
        else:
            time.sleep(2)
else:
    print("Failed to initiate path trace.")

Automating such tasks with Python scripts significantly reduces manual effort, accelerates troubleshooting, and improves overall network reliability. Cisco DNA Center API's extensive capabilities make it an ideal platform for network automation enthusiasts exploring Networkers Home's courses.

Meraki Dashboard API — Network-Wide Automation

Meraki provides a cloud-based API that enables comprehensive automation of network configurations, monitoring, and management across multiple networks. Using the REST API Python network automation approach, engineers can streamline operations for large-scale deployments.

Authenticating with Meraki API

Meraki API uses API keys, which are generated from the dashboard. These keys are passed via headers and are necessary for all API calls:

headers = {
    "X-Cisco-Meraki-API-Key": "",
    "Content-Type": "application/json"
}

Retrieving Network List

Listing all networks within an organization:

org_id = ""
url = f"https://api.meraki.com/api/v1/organizations/{org_id}/networks"
response = requests.get(url, headers=headers)
if response.status_code == 200:
    networks = response.json()
    for network in networks:
        print(f"Network Name: {network['name']}, ID: {network['id']}")
else:
    print("Failed to retrieve networks.")

Automating SSID Creation

Creating or updating SSIDs across multiple networks simplifies wireless management:

network_id = ""
payload = {
    "name": "Automated SSID",
    "ssid": 10,
    "enabled": True,
    "type": "psk",
    "presharedKey": "SecurePass123"
}
response = requests.post(f"https://api.meraki.com/api/v1/networks/{network_id}/ssids", headers=headers, json=payload)
if response.status_code == 201:
    print("SSID created successfully.")

Comparison: Cisco DNA Center API vs Meraki API

Feature Cisco DNA Center API Meraki Dashboard API
Platform On-premises Cisco DNA Center Cloud-based Meraki Dashboard
Use Cases Advanced network automation, device provisioning, path trace Wireless management, network configuration, monitoring across multiple sites
Authentication API tokens, OAuth2 API keys
Complexity Higher, requires on-prem setup More straightforward, cloud managed

Mastering both APIs expands network engineers' capabilities, enabling seamless automation across diverse Cisco platforms. To deepen your understanding, explore training at Networkers Home.

Postman to Python — Converting API Calls to Code

Postman is a popular tool for testing APIs visually before automating them with Python scripts. Learning to translate Postman requests into Python code streamlines the automation process and ensures accuracy.

Exporting Requests from Postman

In Postman, create your API request with all headers, parameters, and body data. Once tested and validated, export the request as code:

  1. Click on "Code" in the Postman interface.
  2. Select "Python - Requests" from the language options.
  3. Copy and adapt the generated code into your script.

Example: Converting a POST Request

Suppose you test creating a network device in Postman; the generated Python code might look like:

import requests

url = "https:///dna/intent/api/v1/network-device"
headers = {
    "X-Auth-Token": "",
    "Content-Type": "application/json"
}
payload = {
    "id": "DeviceID",
    "hostname": "Switch1",
    "type": "Cisco Catalyst"
}
response = requests.post(url, headers=headers, json=payload)
print(response.status_code, response.json())

Advantages of Using Postman for Python Automation

  • Quickly test and debug API calls.
  • Generate accurate request code snippets.
  • Maintain consistency across scripts and API versions.

Integrating Postman into your workflow accelerates development and enhances reliability of network automation scripts, a skill highly valued at Networkers Home.

Pagination, Rate Limiting & Error Handling for APIs

Efficient network automation requires handling large data sets, respecting API rate limits, and implementing robust error handling. These practices ensure scripts are resilient and avoid service disruptions.

Pagination

APIs often paginate responses when returning large datasets. Handling pagination involves iteratively requesting subsequent pages until all data is retrieved. For example, Cisco DNA Center API supports parameters like offset and limit:

def get_all_devices():
    devices = []
    offset = 0
    limit = 100
    while True:
        url = f"https:///dna/intent/api/v1/network-device?offset={offset}&limit={limit}"
        response = requests.get(url, headers=headers)
        data = response.json()
        devices.extend(data.get('response', []))
        if len(data.get('response', [])) < limit:
            break
        offset += limit
    return devices

Rate Limiting

Most APIs impose rate limits to prevent abuse. To avoid hitting limits, include delays or implement exponential backoff strategies:

import time

for i in range(100):
    response = requests.get(some_url, headers=headers)
    if response.status_code == 429:
        retry_after = int(response.headers.get('Retry-After', 1))
        time.sleep(retry_after)
    else:
        process_response(response)
    time.sleep(0.5)  # Slight delay between requests

Error Handling

Always check response status codes and handle errors gracefully:

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    data = response.json()
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"Request failed: {err}")

Incorporating these techniques ensures your network automation scripts are scalable, reliable, and compliant with API policies. For detailed tutorials, visit Networkers Home Blog.

Practice: Build a Network Dashboard from API Data

Creating a network dashboard consolidates data from multiple APIs, providing real-time visibility into device status, network health, and configurations. This hands-on project exemplifies REST API Python network automation in action.

Step 1: Data Collection

Use APIs from Cisco DNA Center and Meraki to fetch device inventories, network statuses, and client data:

# Fetch Cisco DNA Center devices
devices = get_all_devices()

# Fetch Meraki networks
meraki_networks = get_meraki_networks()

Step 2: Data Processing

Aggregate data into a structured format, such as pandas DataFrame or JSON, for visualization:

import pandas as pd

df_devices = pd.DataFrame(devices)
df_networks = pd.DataFrame(meraki_networks)

Step 3: Visualization

Use libraries like Plotly or Dash to create interactive dashboards:

import dash
from dash import html, dcc

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("Network Devices Dashboard"),
    dcc.Graph(
        id='device-status',
        figure=generate_device_status_chart(df_devices)
    ),
    # Additional components
])

if __name__ == '__main__':
    app.run_server(debug=True)

Step 4: Automation & Alerts

Integrate scripts to update the dashboard periodically and send alerts for anomalies, such as unreachable devices or high latency.

This end-to-end project demonstrates the power of REST APIs in network automation, empowering engineers to build scalable, real-time monitoring solutions. Enroll in courses at Networkers Home to master these skills.

Key Takeaways

  • Understanding HTTP methods and status codes is essential for effective REST API Python network automation.
  • The Python requests library simplifies API interactions, enabling GET, POST, PUT, and DELETE operations.
  • Secure authentication using API keys, tokens, and OAuth2 is vital for accessing network APIs safely.
  • Cisco DNA Center API and Meraki API provide extensive capabilities for device management and network automation.
  • Converting Postman requests to Python scripts accelerates development and ensures accuracy.
  • Handling pagination, rate limits, and errors ensures robust, scalable automation scripts.
  • Building dashboards from API data consolidates network visibility and improves operational efficiency.

Frequently Asked Questions

What are the primary benefits of using REST APIs for network automation?

REST APIs enable programmatic control over network devices and platforms, reducing manual configuration errors, increasing speed, and allowing for scalable automation workflows. They facilitate integration between different tools and platforms, providing real-time data access and control. This approach enhances operational efficiency, supports dynamic network environments, and enables proactive management through automation scripts written in Python, which are easier to develop and maintain compared to traditional CLI-based methods.

How do I ensure security when automating network APIs with Python?

Security begins with proper authentication using API keys, OAuth2 tokens, or secure credentials stored in environment variables. Always use HTTPS to encrypt data in transit, and avoid hard-coding sensitive information in scripts. Implement token refresh mechanisms for OAuth2 and restrict API access permissions based on principle of least privilege. Regularly rotate API keys and tokens, monitor API usage logs for anomalies, and follow best practices outlined in network security standards. These measures ensure your automation workflows remain secure from unauthorized access and data breaches.

Can I automate configuration changes across multiple network vendors using REST APIs?

While REST APIs are widely supported by many network vendors like Cisco and Meraki, each platform has its own API specifications and authentication methods. To automate across multiple vendors, leverage vendor-specific APIs and consider creating abstraction layers or a unified scripting framework that handles different API calls seamlessly. Tools like Ansible, Python libraries, or custom scripts can orchestrate multi-vendor automation, but understanding each platform’s API nuances is critical. Enrolling in comprehensive courses at Networkers Home can equip you with the skills needed for such complex automation scenarios.

Ready to Master Python for Network Engineers?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and 100% placement support.

Explore Course