raghavNCI
commited on
Commit
·
37c8516
1
Parent(s):
24717ec
try except added
Browse files
routes.py
CHANGED
@@ -15,21 +15,32 @@ def get_news_by_category(category: str, limit: int = 5):
|
|
15 |
"max": limit,
|
16 |
"token": GNEWS_API_KEY
|
17 |
}
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
|
35 |
@router.get("/")
|
|
|
15 |
"max": limit,
|
16 |
"token": GNEWS_API_KEY
|
17 |
}
|
18 |
+
|
19 |
+
try:
|
20 |
+
response = requests.get(base_url, params=params, timeout=10)
|
21 |
+
response.raise_for_status() # raise exception for non-200 responses
|
22 |
+
data = response.json()
|
23 |
+
|
24 |
+
articles = []
|
25 |
+
for article in data.get("articles", []):
|
26 |
+
articles.append({
|
27 |
+
"title": article["title"],
|
28 |
+
"url": article["url"],
|
29 |
+
"description": article.get("description"),
|
30 |
+
"publishedAt": article["publishedAt"],
|
31 |
+
"image": article.get("image"),
|
32 |
+
"source": article["source"]["name"]
|
33 |
+
})
|
34 |
+
|
35 |
+
return articles
|
36 |
+
|
37 |
+
except requests.exceptions.RequestException as e:
|
38 |
+
print(f"[ERROR] Failed to fetch news: {e}")
|
39 |
+
return {"error": "Failed to fetch news from GNews API."}
|
40 |
+
|
41 |
+
except Exception as e:
|
42 |
+
print(f"[ERROR] Unexpected error: {e}")
|
43 |
+
return {"error": "An unexpected error occurred."}
|
44 |
|
45 |
|
46 |
@router.get("/")
|