PYTHON
Send JSON Data to an API with Python Requests
Discover how to perform a POST request to an API using Python's popular `requests` library, sending a JSON payload and handling the API's response data efficiently.
import requests
import json
def post_json_data(url, payload, api_key=None):
headers = {'Content-Type': 'application/json'}
if api_key:
headers['Authorization'] = f'Bearer {api_key}' # Or 'x-api-key': api_key
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
print(f"Status Code: {response.status_code}")
print(f"Response JSON: {response.json()}")
return response.json()
except requests.exceptions.HTTPError as errh:
print(f"HTTP Error: {errh}")
print(f"Response content: {response.text}") # Access response text for more details
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"Something went wrong: {err}")
return None
# Example usage:
API_URL = 'https://api.example.com/items'
MY_API_KEY = 'your_secret_api_key' # Replace with your actual API key
data_to_send = {
'name': 'New Item',
'description': 'This is a description for the new item.'
}
result = post_json_data(API_URL, data_to_send, MY_API_KEY)
if result:
print("API call successful. Result:", result)
else:
print("API call failed.")
How it works: This Python snippet demonstrates how to send JSON data to an API using the `requests` library. It constructs a dictionary `payload` and passes it directly to the `json` parameter of `requests.post()`, which automatically handles serialization to JSON and sets the `Content-Type` header. It also includes adding an authorization header and robust error handling for various `requests` exceptions, including `HTTPError` for server-side errors, `ConnectionError` for network issues, and `Timeout` for request timeouts.