examples.md•8.29 kB
# News Aggregator API - Usage Examples
This document provides practical examples for using the News Aggregator API endpoints.
## News Endpoints
### Get Top News Articles
Retrieve the most relevant news articles, optionally filtered by category, source, or language.
```bash
# Get top 10 news articles
curl -X GET "http://localhost:3000/api/news/top"
# Get top 5 technology news articles
curl -X GET "http://localhost:3000/api/news/top?limit=5&category=technology"
# Get top business news from a specific source
curl -X GET "http://localhost:3000/api/news/top?category=business&source=Bloomberg"
```
Response:
```json
{
"success": true,
"data": {
"articles": [
{
"id": 1,
"uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Apple Announces New iPhone 15 Pro",
"description": "Apple today announced the iPhone 15 Pro with an A17 chip and improved cameras.",
"url": "https://example.com/apple-iphone-15",
"imageUrl": "https://example.com/images/iphone15.jpg",
"source": "TechCrunch",
"publishedAt": "2025-04-15T10:30:00Z",
"categories": "technology,apple,smartphones",
"language": "en",
"readCount": 1250,
"relevanceScore": 0.92,
"sentiment": 0.7
},
// More articles...
],
"total": 42
}
}
```
### Get All News Articles
Retrieve all news articles with advanced filtering options.
```bash
# Get all news with pagination
curl -X GET "http://localhost:3000/api/news/all?limit=20&offset=40"
# Search for specific terms in articles
curl -X GET "http://localhost:3000/api/news/all?search=artificial+intelligence"
# Filter by date range
curl -X GET "http://localhost:3000/api/news/all?fromDate=2025-04-01T00:00:00Z&toDate=2025-04-30T23:59:59Z"
```
### Get Similar News Articles
Find articles similar to a specific article by UUID.
```bash
# Get articles similar to an article with a specific UUID
curl -X GET "http://localhost:3000/api/news/similar/a1b2c3d4-e5f6-7890-abcd-ef1234567890"
```
### Get News Article by UUID
Retrieve a specific article by its UUID.
```bash
# Get a specific article
curl -X GET "http://localhost:3000/api/news/uuid/a1b2c3d4-e5f6-7890-abcd-ef1234567890"
```
### Get News Sources
Retrieve a list of all available news sources.
```bash
# Get all news sources
curl -X GET "http://localhost:3000/api/news/sources"
# Search for specific news sources
curl -X GET "http://localhost:3000/api/news/sources?search=tech"
```
## Cache Management Endpoints
### Get Cache Statistics
Retrieve statistics about the cache system.
```bash
# Get cache stats
curl -X GET "http://localhost:3000/api/cache/stats"
```
### Clear Entire Cache
Remove all cached data.
```bash
# Clear all cache
curl -X DELETE "http://localhost:3000/api/cache/clear"
```
### Clear Cache by Type
Clear the cache for a specific content type.
```bash
# Clear cache for top news
curl -X DELETE "http://localhost:3000/api/cache/clear/top"
# Clear cache for article UUIDs
curl -X DELETE "http://localhost:3000/api/cache/clear/uuid"
```
## Using the API with JavaScript
Here's an example of how to use the API with JavaScript:
```javascript
// Fetch top news articles
async function getTopNews(category = '', limit = 10) {
try {
const url = `http://localhost:3000/api/news/top?limit=${limit}${category ? `&category=${category}` : ''}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data.data.articles;
} catch (error) {
console.error('Error fetching top news:', error);
return [];
}
}
// Search for articles with a specific term
async function searchArticles(term, limit = 20, offset = 0) {
try {
const url = `http://localhost:3000/api/news/all?search=${encodeURIComponent(term)}&limit=${limit}&offset=${offset}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return {
articles: data.data.articles,
total: data.data.total
};
} catch (error) {
console.error('Error searching articles:', error);
return { articles: [], total: 0 };
}
}
// Get a specific article by UUID
async function getArticleByUuid(uuid) {
try {
const response = await fetch(`http://localhost:3000/api/news/uuid/${uuid}`);
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data.data.article;
} catch (error) {
console.error('Error fetching article:', error);
return null;
}
}
```
## Using the API with Python
Here's an example of how to use the API with Python:
```python
import requests
# Base URL for the API
BASE_URL = "http://localhost:3000/api"
# Get top news articles
def get_top_news(category=None, source=None, limit=10):
params = {"limit": limit}
if category:
params["category"] = category
if source:
params["source"] = source
response = requests.get(f"{BASE_URL}/news/top", params=params)
response.raise_for_status() # Raise exception for HTTP errors
data = response.json()
return data["data"]["articles"]
# Search for articles
def search_articles(query, from_date=None, to_date=None, limit=20, offset=0):
params = {
"search": query,
"limit": limit,
"offset": offset
}
if from_date:
params["fromDate"] = from_date
if to_date:
params["toDate"] = to_date
response = requests.get(f"{BASE_URL}/news/all", params=params)
response.raise_for_status()
data = response.json()
return data["data"]["articles"], data["data"]["total"]
# Get similar articles
def get_similar_articles(uuid, limit=5):
params = {"limit": limit}
response = requests.get(f"{BASE_URL}/news/similar/{uuid}", params=params)
response.raise_for_status()
data = response.json()
return data["data"]["articles"]
```
## MCP (Multi-Consumer Protocol) Integration
The News Aggregator API follows MCP architecture principles, making it ideal for agent integrations:
```javascript
// Example agent code that consumes the News Aggregator API
class NewsAgent {
constructor(baseUrl = 'http://localhost:3000/api') {
this.baseUrl = baseUrl;
}
// Monitor for new articles on a topic
async monitorTopic(topic, interval = 300000) { // Check every 5 minutes
let lastCheckedTime = new Date();
setInterval(async () => {
try {
// Get articles newer than the last check time
const fromDate = lastCheckedTime.toISOString();
lastCheckedTime = new Date();
const url = `${this.baseUrl}/news/all?category=${topic}&fromDate=${fromDate}&sort=publishedAt&order=desc`;
const response = await fetch(url);
const data = await response.json();
if (data.data.articles.length > 0) {
// Process new articles
this.processNewArticles(data.data.articles);
}
} catch (error) {
console.error('Error in monitoring:', error);
}
}, interval);
}
async processNewArticles(articles) {
// Agent-specific logic for processing articles
for (const article of articles) {
// Example: Extract entities, analyze sentiment, etc.
console.log(`Processing: ${article.title}`);
// For each article, you might fetch similar articles
if (article.relevanceScore > 0.8) {
const similar = await this.getSimilarArticles(article.uuid);
// Create connections between related articles
}
}
}
async getSimilarArticles(uuid) {
const response = await fetch(`${this.baseUrl}/news/similar/${uuid}`);
const data = await response.json();
return data.data.articles;
}
}
// Usage
const agent = new NewsAgent();
agent.monitorTopic('technology');
```
This document provides a starting point for integrating with the News Aggregator API. For more details, refer to the OpenAPI documentation at `/docs`.