|
import requests |
|
import os |
|
from typing import List, Dict, Any, Optional |
|
import streamlit as st |
|
|
|
|
|
@st.cache_data(ttl=3600) |
|
def get_top_stories(category: str = "home") -> List[Dict[str, Any]]: |
|
""" |
|
Fetch top stories from the NYT API for a given category. |
|
|
|
Args: |
|
category: News category (e.g., "home", "world", "politics") |
|
|
|
Returns: |
|
List of article dictionaries |
|
""" |
|
|
|
api_key = os.environ.get("NYT_API_KEY") |
|
|
|
|
|
if not api_key: |
|
try: |
|
api_key = st.secrets["NYT_API_KEY"] |
|
except Exception: |
|
st.error("NYT API key not found. Please set the NYT_API_KEY environment variable or in Streamlit secrets.") |
|
return [] |
|
|
|
|
|
url = f"https://api.nytimes.com/svc/topstories/v2/{category}.json" |
|
|
|
|
|
try: |
|
response = requests.get(url, params={"api-key": api_key}) |
|
response.raise_for_status() |
|
|
|
|
|
data = response.json() |
|
|
|
|
|
articles = [ |
|
article for article in data.get("results", []) |
|
if article.get("multimedia") and len(article.get("multimedia", [])) > 0 |
|
] |
|
|
|
|
|
processed_articles = [] |
|
for article in articles[:10]: |
|
processed_article = { |
|
"title": article.get("title", ""), |
|
"abstract": article.get("abstract", ""), |
|
"url": article.get("url", ""), |
|
"image_url": next((media.get("url") for media in article.get("multimedia", []) |
|
if media.get("format") == "superJumbo"), None), |
|
"section": article.get("section", ""), |
|
"published_date": article.get("published_date", "") |
|
} |
|
processed_articles.append(processed_article) |
|
|
|
return processed_articles |
|
|
|
except requests.exceptions.RequestException as e: |
|
st.error(f"Error fetching NYT articles: {e}") |
|
return [] |