-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
43 lines (36 loc) · 1.22 KB
/
main.py
File metadata and controls
43 lines (36 loc) · 1.22 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
import requests
import json
import sys
def fetch_api_data(url, params=None, headers=None):
"""
Fetch data from an HTTP API endpoint
Args:
url (str): The API endpoint URL
params (dict, optional): Query parameters
headers (dict, optional): HTTP headers
Returns:
dict: JSON response data or None if error
"""
try:
response = requests.get(url, params=params, headers=headers)
response.raise_for_status() # Raises an HTTPError for bad responses
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching data from API: {e}", file=sys.stderr)
return None
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}", file=sys.stderr)
return None
def main():
# Example usage - you can modify this to fetch from your desired API
api_url = "https://api.github.com" # Example API
print(f"Fetching data from {api_url}...")
data = fetch_api_data(api_url)
if data:
print("Successfully fetched data:")
print(json.dumps(data, indent=2))
else:
print("Failed to fetch data from API")
sys.exit(1)
if __name__ == "__main__":
main()