Example output
Here's a Python code snippet that performs an API request to the endpoint "https://api.example.com/data." The code uses the `requests` library to handle the request, includes authentication with an API key, and implements error handling, timeouts, and retries.
```python
import requests
from requests.exceptions import HTTPError, Timeout, RequestException
import time
# Constants
API_URL = "https://api.example.com/data"
API_KEY = "your_api_key_here" # Replace with your actual API key
TIMEOUT = 5 # seconds
MAX_RETRIES = 3
RETRY_DELAY = 2 # seconds
def fetch_data_from_api():
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
for attempt in range(MAX_RETRIES):
try:
response = requests.get(API_URL, headers=headers, timeout=TIMEOUT)
# Raise an HTTPError if the HTTP request returned an unsuccessful status code
response.raise_for_status()
# Attempt to parse the JSON response
try:
data = response.json()
if not data:
print("Received an empty response.")
else:
return data
except ValueError:
print("Malformed JSON response received.")
return None
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except Timeout:
print("Request timed out.")
except RequestException as req_err:
print(f"Request error: {req_err}")
# Retry after a delay if not the last attempt
if attempt < MAX_RETRIES - 1:
print(f"Retrying in {RETRY_DELAY} seconds...")
time.sleep(RETRY_DELAY)
else:
print("Max retries reached. Exiting.")
return None
# Example usage
if __name__ == "__main__":
result = fetch_data_from_api()
if result:
print("Data received from API:")
print(result)
else:
print("Failed to fetch data from the API.")
```
### Explanation
1. **Imports and Constants**: The code imports necessary modules (`requests` and `time`) and sets constants such as `API_URL`, `API_KEY`, `TIMEOUT`, `MAX_RETRIES`, and `RETRY_DELAY`.
2. **Headers and Authorization**: It constructs a header with the API key for authentication.
3. **Retry Logic**: The code attempts to fetch data from the API up to `MAX_RETRIES` times, with a delay (`RETRY_DELAY`) between each attempt if an error occurs.
4. **Error Handling**:
- **HTTP Errors**: Catches HTTP-related errors (e.g., 404, 500).
- **Timeouts**: Handles request timeouts.
- **Request Exceptions**: Catches other request-related errors.
5. **Response Handling**:
- Checks if the response is successful (`response.raise_for_status()`).
- Attempts to parse the response as JSON.
- Handles cases where the JSON response is empty or malformed.
6. **Example Usage**: Demonstrates how to use the `fetch_data_from_api()` function to get data from the API.
### Testing the Code
To test the code, replace `"your_api_key_here"` with an actual API key and ensure that the API endpoint is accessible. You can run the script to see if it successfully fetches data from the API and handles any errors appropriately.