69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
"""
|
|
Blog API endpoints.
|
|
Job ID: MTAD-IMPL-2025-11-18-CL
|
|
"""
|
|
|
|
from fastapi import APIRouter, HTTPException, status
|
|
import feedparser
|
|
import httpx
|
|
from datetime import datetime
|
|
from time import mktime
|
|
|
|
router = APIRouter()
|
|
|
|
# TODO: Get this from settings/env
|
|
RSS_FEED_URL = "https://morethanadiagnosis.org/feed/" # Placeholder, need actual URL
|
|
|
|
@router.get("/rss")
|
|
async def get_blog_rss():
|
|
"""Fetch and parse blog posts from WordPress RSS feed."""
|
|
async with httpx.AsyncClient() as client:
|
|
try:
|
|
response = await client.get(RSS_FEED_URL)
|
|
response.raise_for_status()
|
|
except httpx.RequestError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail=f"Error fetching blog feed: {exc}"
|
|
)
|
|
except httpx.HTTPStatusError as exc:
|
|
raise HTTPException(
|
|
status_code=exc.response.status_code,
|
|
detail=f"Error fetching blog feed: {exc}"
|
|
)
|
|
|
|
feed = feedparser.parse(response.text)
|
|
|
|
posts = []
|
|
for entry in feed.entries:
|
|
# Parse published date
|
|
published_at = None
|
|
if hasattr(entry, 'published_parsed'):
|
|
published_at = datetime.fromtimestamp(mktime(entry.published_parsed))
|
|
|
|
# Extract image if available (WordPress often puts it in content or media:content)
|
|
image_url = None
|
|
if 'media_content' in entry:
|
|
image_url = entry.media_content[0]['url']
|
|
elif 'links' in entry:
|
|
for link in entry.links:
|
|
if link.get('rel') == 'enclosure' and link.get('type', '').startswith('image/'):
|
|
image_url = link['href']
|
|
break
|
|
|
|
posts.append({
|
|
"id": entry.get("id", entry.get("link")),
|
|
"title": entry.get("title"),
|
|
"link": entry.get("link"),
|
|
"published_at": published_at,
|
|
"summary": entry.get("summary"),
|
|
"content": entry.get("content", [{"value": ""}])[0]["value"],
|
|
"image_url": image_url,
|
|
"author": entry.get("author")
|
|
})
|
|
|
|
return {
|
|
"title": feed.feed.get("title", "Blog"),
|
|
"description": feed.feed.get("description", ""),
|
|
"items": posts
|
|
}
|