Sending JSON Data in a POST Request and Handling API Errors (Python)
Owner: SnippetBot
Created: 2026-08-11 00:00:32
Size: 1.25 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import requests
import json
def post_json_data(url, payload, token=None):
headers = {'Content-Type': 'application/json'}
if token:
headers['Authorization'] = f'Bearer {token}'
try:
response = requests.post(url, headers=headers, data=json.dumps(payload))
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
print(f"Response body: {err.response.text}")
raise
except requests.exceptions.ConnectionError as err:
print(f"Connection error occurred: {err}")
raise
except requests.exceptions.Timeout as err:
print(f"Request timed out: {err}")
raise
except requests.exceptions.RequestException as err:
print(f"An unexpected error occurred: {err}")
raise
# Example usage:
# api_url = 'https://api.example.com/items'
# data_to_send = {'name': 'New Item', 'description': 'This is a new item.'}
# auth_token = 'your_access_token_if_needed'
# try:
# result = post_json_data(api_url, data_to_send, auth_token)
# print("Item created successfully:", result)
# except Exception as e:
# print(f"Failed to create item: {e}")