File size: 1,483 Bytes
cad0e2e 6e3bc3c 3be496d cad0e2e 37c8516 cad0e2e 3be496d |
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 |
import os
import requests
from fastapi import APIRouter, Query
from dotenv import load_dotenv
load_dotenv()
router = APIRouter()
GNEWS_API_KEY = os.getenv("GNEWS_API_KEY")
@router.get("/news/category/{category}")
def get_news_by_category(category: str, limit: int = 5):
base_url = "https://gnews.io/api/v4/top-headlines"
params = {
"topic": category,
"lang": "en",
"max": limit,
"token": GNEWS_API_KEY
}
try:
response = requests.get(base_url, params=params, timeout=10)
response.raise_for_status() # raise exception for non-200 responses
data = response.json()
articles = []
for article in data.get("articles", []):
articles.append({
"title": article["title"],
"url": article["url"],
"description": article.get("description"),
"publishedAt": article["publishedAt"],
"image": article.get("image"),
"source": article["source"]["name"]
})
return articles
except requests.exceptions.RequestException as e:
print(f"[ERROR] Failed to fetch news: {e}")
return {"error": "Failed to fetch news from GNews API."}
except Exception as e:
print(f"[ERROR] Unexpected error: {e}")
return {"error": "An unexpected error occurred."}
@router.get("/")
async def root():
return {"message": "LucidFeed backend is up and running!"}
|