200-901 Question 53
Single answerYou are building a Python script to fetch data from a REST API using the requests library. The API endpoint requires an HTTP GET request and includes an API key for authentication in the headers. Which of the following Python code snippets correctly performs this task?
- A
import requests response = requests.get('https://api.example.com/data', headers={'Authorization': 'Bearer API_KEY'}) print(response.json())
- B
import requests response = requests.post('https://api.example.com/data', headers={'Authorization': 'Bearer API_KEY'}) print(response.json())
- C
import requests response = requests.get('https://api.example.com/data', headers={'API_KEY': 'Bearer API_KEY'}) print(response.json())
- D
import requests response = requests.get('https://api.example.com/data', params={'Authorization': 'Bearer API_KEY'}) print(response.json())
Show answer and explanation
Correct answer: A
Explanation
To perform an HTTP GET request using the requests library, the requests.get() method must be used. The API key is typically included in the Authorization header in the format Bearer API_KEY for authentication. Any deviation from these requirements, such as using the wrong HTTP method or placing the API key in the wrong location, will result in an incorrect implementation.
- A. Correct.
This option is correct because it uses the
requests.get()method to perform an HTTP GET request and correctly includes the API key in theAuthorizationheader. - B. Incorrect.
This option is incorrect because it uses the
requests.post()method instead of therequests.get()method to make the request. The API endpoint specifically requires an HTTP GET request. - C. Incorrect.
This option is incorrect because it uses the wrong key (
API_KEY) in the headers. The correct header key for including an API key in this scenario isAuthorization. - D. Incorrect.
This option is incorrect because it places the API key in the
paramsargument instead of theheadersargument. Theparamsargument is used for query string parameters, not for authentication headers.