Construct a Python script that calls a REST API using the requests library

📘Cisco DevNet Associate (200-901 DEVASC)


This topic is very important for the Cisco DevNet Associate (200-901 DEVASC) exam. You must understand how to use Python to send HTTP requests to REST APIs and process the responses.

In this guide, we will cover:

  • What is a REST API
  • What is the Python requests library
  • How to install and import requests
  • How to send GET, POST, PUT, DELETE requests
  • How to send headers and authentication
  • How to send JSON data
  • How to handle responses
  • How to check HTTP status codes
  • How to handle errors
  • How to parse JSON responses
  • Best practices for DEVASC exam

Everything is explained in simple English.


1. What Is a REST API?

A REST API (Representational State Transfer API) is a web service that allows applications to communicate over HTTP.

In networking and IT environments, REST APIs are commonly used to:

  • Get device information from a network controller
  • Create users in a cloud platform
  • Update firewall rules
  • Retrieve monitoring data
  • Configure routers or switches programmatically

For example:

  • Cisco DNA Center provides REST APIs to manage enterprise networks.
  • Cisco Meraki Dashboard provides REST APIs for cloud-managed devices.
  • Webex provides APIs to manage rooms, messages, and users.

Your Python script acts as a client, sending requests to these APIs.


2. What Is the Python requests Library?

The requests library is a popular Python library used to send HTTP requests easily.

It supports:

  • GET
  • POST
  • PUT
  • DELETE
  • Headers
  • Authentication
  • JSON data
  • Response handling

It is simple and commonly used in automation scripts.


3. Installing and Importing Requests

Install the library:

pip install requests

Import in Python:

import requests

For DEVASC exam, you should recognize this structure immediately.


4. Basic Structure of a Python REST API Call

A simple script usually follows this structure:

import requestsurl = "https://api.example.com/resource"response = requests.get(url)print(response.status_code)
print(response.text)

Steps:

  1. Import requests
  2. Define the API URL
  3. Send the HTTP request
  4. Store the response
  5. Check status code
  6. Process response data

5. Sending a GET Request

GET is used to retrieve data.

Example:

import requestsurl = "https://api.example.com/devices"response = requests.get(url)print("Status Code:", response.status_code)
print("Response Body:", response.text)

Important Response Attributes

  • response.status_code
  • response.text
  • response.json()
  • response.headers

For the exam, you must understand what each does.


6. Parsing JSON Response

Most REST APIs return JSON data.

Instead of:

print(response.text)

Use:

data = response.json()
print(data)

Why?

  • response.text gives raw text.
  • response.json() converts JSON into a Python dictionary.

Example:

data = response.json()
print(data["name"])

7. Sending Headers

Many APIs require headers such as:

  • Authorization
  • Content-Type
  • Accept

Example:

import requestsurl = "https://api.example.com/devices"headers = {
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
"Content-Type": "application/json"
}response = requests.get(url, headers=headers)print(response.status_code)

Headers are passed using the headers= parameter.

For DEVASC, remember:

requests.get(url, headers=headers)

8. Authentication Methods

APIs require authentication. Common types:

1. API Key (Bearer Token)

headers = {
"Authorization": "Bearer ACCESS_TOKEN"
}

2. Basic Authentication

from requests.auth import HTTPBasicAuthresponse = requests.get(url, auth=HTTPBasicAuth("username", "password"))

For the exam, understand both methods.


9. Sending a POST Request

POST is used to create resources.

Example: Creating a new user in a system.

import requestsurl = "https://api.example.com/users"headers = {
"Content-Type": "application/json"
}payload = {
"name": "John",
"email": "john@example.com"
}response = requests.post(url, json=payload, headers=headers)print(response.status_code)
print(response.json())

Important:

  • Use json=payload to automatically convert dictionary to JSON.
  • Do NOT manually convert using json.dumps() unless required.

10. PUT and DELETE Requests

PUT (Update resource)

response = requests.put(url, json=payload, headers=headers)

DELETE (Remove resource)

response = requests.delete(url, headers=headers)

DEVASC expects you to recognize these methods.


11. Checking HTTP Status Codes

Always verify if request was successful.

Common codes:

  • 200 → OK
  • 201 → Created
  • 204 → No Content
  • 400 → Bad Request
  • 401 → Unauthorized
  • 403 → Forbidden
  • 404 → Not Found
  • 500 → Server Error

Example:

if response.status_code == 200:
print("Success")
else:
print("Error:", response.status_code)

12. Error Handling with try/except

Best practice is to handle errors properly.

import requeststry:
response = requests.get(url)
response.raise_for_status()
data = response.json()
print(data)except requests.exceptions.HTTPError as err:
print("HTTP error:", err)except requests.exceptions.ConnectionError:
print("Connection error")except requests.exceptions.Timeout:
print("Timeout error")except requests.exceptions.RequestException as err:
print("General error:", err)

For DEVASC, understand:

  • raise_for_status()
  • Different exception types

13. Using Query Parameters

Sometimes APIs require query parameters.

Example:

https://api.example.com/devices?status=active

Python method:

params = {
"status": "active"
}response = requests.get(url, params=params)

Requests automatically appends parameters.


14. Full Example Script (Exam-Level Structure)

import requestsurl = "https://api.example.com/devices"headers = {
"Authorization": "Bearer ACCESS_TOKEN",
"Content-Type": "application/json"
}try:
response = requests.get(url, headers=headers)
response.raise_for_status() if response.status_code == 200:
devices = response.json()
for device in devices:
print(device["name"])except requests.exceptions.RequestException as e:
print("Error occurred:", e)

This script shows:

  • Import
  • URL
  • Headers
  • GET request
  • Status code validation
  • JSON parsing
  • Exception handling

This is exactly the type of structure DEVASC expects you to understand.


15. Best Practices for DEVASC Exam

You must understand:

✔ Difference between GET, POST, PUT, DELETE
✔ How to send headers
✔ How to send JSON data
✔ How to parse JSON response
✔ How to check status codes
✔ How authentication works
✔ How to handle errors
✔ How query parameters work
✔ Structure of a Python REST script


16. Common Exam Mistakes

Be careful about:

  • Forgetting headers=
  • Using data= instead of json=
  • Not checking status code
  • Not converting JSON properly
  • Not handling authentication correctly
  • Forgetting response.raise_for_status()

17. Why This Is Important in Real IT Environments

In modern enterprise networks:

  • Network engineers automate configuration using APIs.
  • DevOps teams integrate network systems with cloud tools.
  • Monitoring systems pull data via REST APIs.
  • Security systems update policies via APIs.

Understanding Python + REST APIs is a core DevNet skill.


Final Summary

To pass this DEVASC topic, you must be comfortable with:

  1. Importing requests
  2. Sending HTTP methods (GET, POST, PUT, DELETE)
  3. Adding headers and authentication
  4. Sending JSON payloads
  5. Parsing JSON responses
  6. Checking HTTP status codes
  7. Handling errors using try/except
  8. Using query parameters

If you understand these clearly and can read Python REST scripts confidently, you are fully prepared for this exam section.

Buy Me a Coffee