200-901 Question 54
Single answerYou are tasked with creating a Python script to retrieve data from a REST API endpoint that requires an API key for authentication. The API endpoint is 'https://api.example.com/data'. The API key must be passed as a header named 'Authorization' in the format 'Bearer <API_KEY>'. Which of the following Python scripts correctly retrieves the data using the requests library?
- A
import requests
api_key = 'your_api_key_here' url = 'https://api.example.com/data' headers = {'Authorization': 'Bearer ' + api_key} response = requests.get(url, headers=headers) print(response.json())
- B
import requests
api_key = 'your_api_key_here' url = 'https://api.example.com/data' response = requests.get(url, headers={'Authorization': api_key}) print(response.json())
- C
import requests
api_key = 'your_api_key_here' url = 'https://api.example.com/data' response = requests.get(url, auth=('Authorization', 'Bearer ' + api_key)) print(response.json())
- D
import requests
api_key = 'your_api_key_here' url = 'https://api.example.com/data' response = requests.get(url, data={'Authorization': 'Bearer ' + api_key}) print(response.json())
Show answer and explanation
Correct answer: A
Explanation
The correct answer is the script that properly constructs the HTTP header with the 'Authorization' key and the 'Bearer <API_KEY>' value, and then passes this header in the requests.get() call. The other options either omit the required 'Bearer ' prefix, misuse the 'auth' parameter, or incorrectly use the 'data' parameter for headers.
- A. Correct.
This is the correct script. It correctly constructs the headers dictionary with the 'Authorization' key and the 'Bearer <API_KEY>' value. The requests.get() method is correctly called with the url and headers arguments, and the response is parsed as JSON.
- B. Incorrect.
This script is incorrect because it passes only the API key as the value for the 'Authorization' header without the required 'Bearer ' prefix, which is part of the authentication format.
- C. Incorrect.
This script is incorrect because the requests.get() method does not use the 'auth' parameter in this way. The 'auth' parameter is meant for basic authentication, not for passing headers.
- D. Incorrect.
This script is incorrect because it incorrectly uses the 'data' parameter instead of the 'headers' parameter. The 'data' parameter is used to send form-encoded data in the body of the request, not for headers.