350-401 Question 310
Single answerYou are tasked with creating a Python script that interacts with a network device using a REST API. The script must send a GET request to retrieve the device's interface information and then print the response data in JSON format. Which of the following code snippets correctly achieves this?
- A
import requests response = requests.get('http://device-ip/api/interfaces') print(response.json())
- B
import requests response = requests.get('http://device-ip/api/interfaces') print(response.text())
- C
import json response = requests.get('http://device-ip/api/interfaces') print(json.dumps(response.json()))
- D
import requests response = requests.get('http://device-ip/api/interfaces') print(response.content)
Show answer and explanation
Correct answer: A
Explanation
The requests library is commonly used in Python for making HTTP requests. To retrieve and display the JSON response from a REST API, the response.json() method should be used, as it parses the JSON data directly. Using other methods like response.text() or response.content would not display the data in the required JSON format.
- A. Correct.
This is the correct answer. The
requestslibrary is used to send a GET request to the REST API, andresponse.json()correctly parses the JSON response from the API to print it in JSON format. - B. Incorrect.
This is incorrect because
response.text()would print the response as a raw string, not in JSON format. - C. Incorrect.
This is incorrect because the
jsonlibrary is not required here. Therequestslibrary already provides theresponse.json()method for parsing JSON, making this approach unnecessary. - D. Incorrect.
This is incorrect because
response.contentreturns the raw bytes of the response, not the JSON-formatted data.