200-901 Question 86
Single answerYou are tasked with automating the process of retrieving a list of devices from a network management system using its REST API. The system requires an API key for authentication, which must be included in the HTTP headers. Below is a set of requirements for the operation:
- Use the 'requests' library in Python.
- The API endpoint is 'https://api.networkmgmt.local/devices'.
- Include the header 'Authorization' with the value 'Bearer <API_KEY>'.
- Parse the JSON response and print only the device names.
Which code snippet fulfills these requirements?
- A
import requests response = requests.get('https://api.networkmgmt.local/devices') devices = response.json() for device in devices['data']: print(device['name'])
- B
import requests headers = {'Authorization': 'Bearer <API_KEY>'} response = requests.get('https://api.networkmgmt.local/devices', headers=headers) devices = response.json() for device in devices['data']: print(device['name'])
- C
import requests headers = {'Authorization': 'Bearer <API_KEY>'} data = {'filter': 'device_names'} response = requests.post('https://api.networkmgmt.local/devices', headers=headers, json=data) print(response.json())
- D
import requests headers = {'Auth': 'Bearer <API_KEY>'} response = requests.get('https://api.networkmgmt.local/devices', headers=headers) devices = response.json() for device in devices['name']: print(device)
Show answer and explanation
Correct answer: B
Explanation
To retrieve the list of devices, the code needs to use the 'requests.get()' method with the correct API endpoint and the 'Authorization' header containing the API key. The JSON response must be parsed to extract and print the device names. Option 2 is the only code snippet that fulfills all these requirements.
- A. Incorrect.
This option does not include the required 'Authorization' header with the API key, so the request would fail authentication.
- B. Correct.
This option correctly constructs the HTTP headers with the 'Authorization' header and retrieves the devices via a GET request. It also parses the JSON response and prints the device names, meeting all the requirements.
- C. Incorrect.
This option incorrectly uses the POST method instead of GET and includes an unnecessary data payload. The requirements specifically state to use a GET request to retrieve devices.
- D. Incorrect.
This option uses an incorrect header key ('Auth' instead of 'Authorization') and attempts to access a nonexistent key ('name') in the JSON response, which would result in an error.