350-401 Question 312
Select 3A network engineer is tasked with automating the retrieval of interface status from a Cisco switch using a Python script. The following snippet is provided:
import requests
url = 'http://switch.example.com/api/v1/interfaces'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
for interface in data['interfaces']:
print(interface['name'], interface['status'])
else:
print('Failed to retrieve data')
Based on this script, which of the following statements are correct?
- A
The script uses the HTTP GET method to retrieve data from the switch.
- B
The script requires an active API token to authenticate with the switch.
- C
The
response.json()method parses the JSON response from the API. - D
The
data['interfaces']key is guaranteed to exist in the API response. - E
The script will raise an exception if the HTTP response status is not 200.
Show answer and explanation
Correct answers: A, B, C
Explanation
The Python script demonstrates the use of the requests library to interact with a REST API. It uses the HTTP GET method and includes an Authorization header for token-based authentication. The response.json() method is used to parse the API's JSON response. However, the script does not guarantee the existence of the data['interfaces'] key, nor does it raise exceptions for non-200 HTTP status codes. Understanding these fundamental Python components and behavior is critical for automating network tasks.
- A. Correct.
Correct. The
requests.getfunction explicitly uses the HTTP GET method to retrieve data from the provided URL. - B. Correct.
Correct. The Authorization header includes a 'Bearer' token, which is required for API authentication.
- C. Correct.
Correct. The
response.json()method is used to parse the JSON response from the API into a Python dictionary. - D. Incorrect.
Incorrect. The existence of the
data['interfaces']key depends on the API response structure and is not guaranteed unless explicitly validated. - E. Incorrect.
Incorrect. The script simply prints 'Failed to retrieve data' if the HTTP response status is not 200; it does not raise an exception in such cases.