-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.py
More file actions
63 lines (54 loc) · 1.82 KB
/
fetch.py
File metadata and controls
63 lines (54 loc) · 1.82 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
import requests
import json
import os
# Fetch the API Key from environment variables for security
API_KEY = os.getenv('') # Replace with a secure environment variable
BASE_URL = 'https://newsapi.org/v2/top-headlines'
def fetch_news(country='us', category='business'):
params = {
'country': country,
'category': category,
'apiKey': API_KEY
}
response = requests.get(BASE_URL, params=params, timeout=2) # Set a timeout for requests
if response.status_code == 200:
news_data = response.json()
return news_data.get('articles', [])
else:
return []
def lambda_handler(event, context):
try:
# Get country and category from the event
country = event.get('country', 'us')
category = event.get('category', 'business')
# Fetch news articles
articles = fetch_news(country, category)
# Format response
if articles:
formatted_articles = [
{
"title": article.get("title", "No Title"),
"description": article.get("description", "No Description"),
"url": article.get("url", "No URL")
}
for article in articles
]
return {
"statusCode": 200,
"body": json.dumps(formatted_articles)
}
else:
return {
"statusCode": 200,
"body": json.dumps({"message": "No articles found."})
}
except requests.exceptions.RequestException as e:
return {
"statusCode": 500,
"body": json.dumps({"error": f"Request failed: {str(e)}"})
}
except Exception as e:
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}