350-401 Question 313
Single answerA network engineer is tasked with writing a Python script to automate the retrieval of interface status from a Cisco device using the REST API. The engineer needs to parse the JSON response and display only the 'interface' and 'status' fields for each interface. Which Python code snippet accomplishes this task?
- A
import requests response = requests.get('http://device/api/interfaces') data = response.json() for interface in data['interfaces']: print(interface['name'], interface['status'])
- B
import json response = json.load('http://device/api/interfaces') for interface in response['interfaces']: print(interface['name'], interface['status'])
- C
import requests response = requests.get('http://device/api/interfaces') data = response.text for interface in data['interfaces']: print(interface['name'], interface['status'])
- D
import requests response = requests.get('http://device/api/interfaces') data = response.json() for interface in data['interfaces']: print(interface['interface'], interface['status'])
Show answer and explanation
Correct answer: D
Explanation
The correct code snippet uses the 'requests' library to make an HTTP GET request to the Cisco device's REST API, retrieves the JSON response using 'response.json()', and iterates through the 'interfaces' list to extract and print the 'interface' and 'status' fields. Using the correct keys ('interface' and 'status') and properly parsing the JSON response is essential for successfully automating this task.
- A. Incorrect.
This option is almost correct, but the key used ('name') does not match the required key ('interface') for the field names in the JSON response.
- B. Incorrect.
This option incorrectly uses 'json.load' with a URL, which is not valid. The 'json' module is used to parse data, not retrieve it from a URL.
- C. Incorrect.
This option incorrectly uses 'response.text' instead of 'response.json()'. 'response.text' provides raw string data, not a parsed JSON object, so this code would raise an error.
- D. Correct.
This is the correct answer because it correctly uses 'requests.get' to retrieve the data, 'response.json()' to parse the JSON response, and accesses the required 'interface' and 'status' fields correctly.