Your Python equivalent of the cURL command is mostly correct, but here are a few enhancements to improve its efficiency, readability, and error handling:
import requests
# Define the API endpoint
url = "https://api.example.com/data"
# Set up headers
headers = {
"Authorization": "Bearer your_api_key",
"Content-Type": "application/json"
}
# Define the payload
data = {
"key": "value"
}
try:
# Send the request with a timeout to avoid hanging requests
response = requests.post(url, headers=headers, json=data, timeout=10)
# Raise an HTTPError for bad responses (4xx and 5xx)
response.raise_for_status()
# Process the response
print("Success:", response.json())
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError:
print("Connection error. Please check your internet connection.")
except requests.exceptions.Timeout:
print("Request timed out. Try increasing the timeout value.")
except requests.exceptions.RequestException as err:
print(f"An error occurred: {err}")
Improvements Over the Original Code:
Error Handling – Uses response.raise_for_status() to handle HTTP errors properly. Also, try-except blocks catch connection issues, timeouts, and other request-related exceptions.
Timeout – Adds a timeout (timeout=10) to prevent indefinite hanging.
Improved Debugging – Prints specific error messages for different failure cases.
More Readable Structure – Groups variables logically, making the code easier to modify and scale.
This approach ensures that your API request is more robust, efficient, and user-friendly.