-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_post.py
More file actions
89 lines (77 loc) · 2.7 KB
/
api_post.py
File metadata and controls
89 lines (77 loc) · 2.7 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import requests
import json
import sys
import os
# Load environment variables from .env file if it exists
def load_dotenv():
dotenv_path = '.env'
if os.path.exists(dotenv_path):
with open(dotenv_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
key, value = line.split('=', 1)
os.environ.setdefault(key.strip(), value.strip())
load_dotenv()
def post_json(url, token, data):
"""
Send HTTP POST request with JSON body and Bearer token authorization.
Args:
url (str): Target API endpoint.
token (str): Bearer token for Authorization header.
data (dict): JSON-serializable data to send in request body.
Returns:
dict: Parsed JSON response, or None on failure.
"""
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
try:
response = requests.post(url, headers=headers, json=data, timeout=10)
# Raise for HTTP errors (4xx,5xx)
response.raise_for_status()
# Try to parse JSON; if empty or not JSON, return text
try:
return response.json()
except json.JSONDecodeError:
return response.text
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}", file=sys.stderr)
return None
def main():
# Configuration for the specific API
API_URL = "https://isdweb.deltaww.com/api/getUnoNextPeriod"
# Read token from environment variable (loaded from .env or system)
YOUR_TOKEN = os.getenv('API_TOKEN')
if not YOUR_TOKEN:
print("Error: API_TOKEN environment variable not set", file=sys.stderr)
print("Please set it in .env file or export API_TOKEN='your_token_here'", file=sys.stderr)
sys.exit(1)
# JSON payload to send (as provided)
payload = {
"token": YOUR_TOKEN,
"sn": "2514L0170255",
"sensor": None,
"rtData": [],
"dataFormat": "dict",
"tsRange": None,
"dataInterval": "6m"
}
print(f"Sending POST to {API_URL}...")
print(f"Payload: {json.dumps(payload, indent=2)}")
result = post_json(API_URL, YOUR_TOKEN, payload)
if result is not None:
print("Response received:")
# Pretty-print if dict/list, else print raw
if isinstance(result, (dict, list)):
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(result)
else:
print("Failed to get a valid response.", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()