Building Python Scripts for REST API Calls: A Practical Guide (2.9)

Jimin
3 min readNov 21, 2023

--

Introduction

A key skill for network developers, particularly those preparing for the Cisco DevNet Associate Exam, is creating Python scripts to interact with REST APIs. This post will guide you through the process of constructing a Python script that uses the requests library to call a REST API, complete with an example script.

Understanding the Requests Library

  • Overview: The requests library in Python simplifies HTTP requests by abstracting the complexities of making HTTP requests.
  • Installation: If you don’t have the requests library, you can install it via pip:
pip install requests

Constructing the Script

Import the Library

  • Begin by importing the requests library in your Python script.
import requests

Set the API Endpoint

  • Define the URL of the API endpoint you wish to call.
url = 'https://api.example.com/data'

Make the Request

  • Use the appropriate requests method to make a call to the API. For a GET request:
response = requests.get(url)
  • For a POST request, include data:
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=payload)

Handle the Response

  • Process the response from the API. For instance, you can convert a JSON response into a Python dictionary:
data = response.json()
print(data)

Example Script

Fetching User Data

Let’s create a simple script to fetch user data from a REST API:

import requests
def fetch_user_data(user_id):
url = f'https://api.example.com/users/{user_id}'
response = requests.get(url)

if response.status_code == 200;
return response.json()
else:
return f'Error: {response.status_code}'

# Example usage
user_data = fetch_user_data(123)
print(user_data)

This script fetches data for a specified user and prints it. It handles basic error checking by verifying the HTTP response status code.

Configuring a Network Device

Let’s say you want to update the configuration of a network device using its REST API. For this example, we’ll assume the device’s API allows the hostname via a POST request.

import requests
import json

def update_hostname(device_ip, new_hostname, auth_token):
url = f'http://{device_ip}/api/v1/configuration'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {auth_token}'
}
payload = {
'hostname': new_hostname
}

response = requests.post(url, headers=headers, data=json.dumps(payload))

if response.status_code == 200:
print("Successfully updated the hostname.")
else:
print(f"Failed to update hostname. Status Code: {response.status_code}")

# Example usage
device_ip = '192.168.1.100'
new_hostname = 'NewRouterName'
auth_token = 'your_auth_token_here'

update_hostname(device_ip, new_hostname, auth_token)

In this script:

  • We define a function update_hostname that takes the device IP, the new hostname, and an authentication token.
  • The script makes a POST request to the device’s configuration API endpoint.
  • We include an authorization header with a bearer token for security.
  • The response’s status code is checked to determine if the update was successful.

Sending an RPC Command to a Network Device

Imagine you need to retrieve the current status of a network switch using a JSON_RPC API. The API provides a method named getSwitchStatus that you can call to get this information.

import json
import requests

def get_switch_status(switch_ip, rpc_url, rpc_method):
headers = {'Content-Type': 'application/json'}
payload = {
"jsonrpc": "2.0",
"method": rpc_method,
"params": [],
"id": 1
}

response = requests.post(f'http://{switch_ip}/{rpc_url}', headers=headers, data=json.dumps(payload))

if response.status_code == 200:
return response.json()
else:
return f"Error: {response.status_code}"

# Example usage
switch_ip = '192.168.1.50'
rpc_url = 'rpc'
rpc_method = 'getSwitchStatus'

status = get_switch_status(switch_ip, rpc_url, rpc_method)
print(status)

In this script:

  • The get_switch_status function sends a JSON-RPC request to the switch.
  • It constructs a JSON payload with the method getSwitchStatus.
  • The id field in the payload is a number identifying the request; this can be any number and is used to match responses with requests.
  • The functions checks the response status and returns the result.

Conclusion

Writing Python scripts to interact with REST APIs and execute RPC commands is a fundamental skill for modern network development. The requests library makes this task more accessible, enabling you to focus on the logic of your application rather than the intricacies of HTTP communication.

With the completion of Part 2: Understanding and Using APIs, we’ve made significant strides in mastering API interactions and Python scripting for the Cisco DevNet Associate Exam. As we now transition to Part 3: Cisco Platforms and Development, our first stop will be “3.1 Construct a Python script that uses a Cisco SDK given SDK documentation,” where we’ll delve into the practical use of Cisco’s SDKs in network automation. This new section promises to deepen our expertise with a focus on Cisco’s specific technologies and platforms. For a holistic view of our journey and upcoming topics, check out our series overview: Navigating the DevNet Associate Exam (200–901): A Study Series.

--

--

Jimin
Jimin

Written by Jimin

DevOps engineer and tech enthusiast. Sharing tech insights to simplify the complex. Let's connect on LinkedIn! https://www.linkedin.com/in/byun-jimin/