FastAPI / routes.py
raghavNCI
few more .env changes
6e3bc3c
raw
history blame
1.48 kB
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!"}