This guide provides tutorials and code examples for common use cases with the Veritas B2B API.
Quick Links#
JavaScript Examples#
| Example | Description |
|---|---|
| News Aggregator | Build a multi-category news feed with caching |
| Fact Checker | Verify claims and generate fact-check reports |
| Entity Tracker | Track entities and explore relationships |
Python Examples#
| Example | Description |
|---|---|
| News Aggregator | Async news feed with caching |
| Alert Manager | Create and manage alert subscriptions |
Tutorial 1: Building a News Aggregator#
Learn how to build a news aggregation service that fetches articles from multiple categories and displays trending content.
Key Concepts#
- Fetching articles from the Feed API
- Implementing caching for performance
- Using async pagination
- Sorting and filtering articles
JavaScript Implementation#
javascript
import { VeritasClient } from '@veritas/b2b-sdk';
const client = new VeritasClient({ apiKey: 'sk_live_...' });
// Fetch articles from multiple categories in parallel
async function getMultiCategoryFeed() {
const categories = ['politics', 'business', 'technology'];
const results = await Promise.all(
categories.map((category) => client.feed.list({ category, limit: 10 }))
);
// Combine and sort by date
const allArticles = results
.flatMap((r) => r.items)
.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
return allArticles;
}
// Get trending articles
async function getTrending() {
const { items } = await client.feed.trending({
hours: 24,
limit: 10,
});
return items;
}
Python Implementation#
python
import asyncio
from veritas_sdk import VeritasClient
async def get_multi_category_feed(client):
categories = ["politics", "business", "technology"]
# Fetch concurrently
tasks = [
client.feed.list(category=cat, limit=10)
for cat in categories
]
results = await asyncio.gather(*tasks)
# Combine and sort
all_articles = []
for response in results:
all_articles.extend(response["items"])
all_articles.sort(
key=lambda a: a["publishedAt"],
reverse=True
)
return all_articles
Best Practices#
- Cache responses to avoid redundant API calls
- Fetch in parallel when requesting multiple categories
- Use pagination for large result sets
- Implement rate limiting to stay within limits
Tutorial 2: Fact-Checking Service#
Build a service that verifies claims against the fact-check database.
Key Concepts#
- Searching and verifying claims
- Understanding ClaimReview structured data
- Batch verification
- Generating fact-check reports
JavaScript Implementation#
javascript
import { VeritasClient } from '@veritas/b2b-sdk';
const client = new VeritasClient({ apiKey: 'sk_live_...' });
// Verify a single claim
async function verifyClaim(statement) {
const claim = await client.claims.verify(statement);
if (!claim) {
return { verified: false, statement };
}
return {
verified: true,
statement,
verdict: claim.verdict,
confidence: claim.confidence,
evidence: claim.evidenceSummary,
source: claim.claimReview.author.name,
};
}
// Batch verify multiple claims
async function verifyMultiple(statements) {
const results = [];
for (const statement of statements) {
const result = await verifyClaim(statement);
results.push(result);
}
return results;
}
// Usage
const claims = [
'Vaccines cause autism',
'The earth is flat',
'COVID-19 originated in a lab',
];
const results = await verifyMultiple(claims);
for (const result of results) {
if (result.verified) {
console.log(`${result.verdict}: ${result.statement}`);
} else {
console.log(`NOT VERIFIED: ${result.statement}`);
}
}
Understanding Verdicts#
| Verdict | Description |
|---|---|
true |
Claim is accurate |
mostly_true |
Claim is mostly accurate with minor issues |
mixed |
Claim contains both true and false elements |
misleading |
Claim is technically true but misleading |
mostly_false |
Claim is mostly inaccurate |
false |
Claim is completely false |
unverifiable |
Claim cannot be verified |
satire |
Claim is satire/parody |
Tutorial 3: Entity Tracking Dashboard#
Build a dashboard to track entities (people, organizations) in the news.
Key Concepts#
- Searching entities by type
- Fetching entity relationships
- Monitoring entity mentions
- Analyzing coverage patterns
JavaScript Implementation#
javascript
import { VeritasClient } from '@veritas/b2b-sdk';
const client = new VeritasClient({ apiKey: 'sk_live_...' });
// Search for a person
async function findPerson(name) {
const { entities } = await client.entities.search({
q: name,
type: 'person',
limit: 5,
});
return entities;
}
// Get entity profile with relationships
async function getEntityProfile(entityId) {
const { entity, relationships } =
await client.entities.getWithRelationships(entityId);
return {
entity,
relationships,
relatedOrganizations: relationships.filter(
(r) =>
r.targetEntityType === 'organization' ||
r.sourceEntityType === 'organization'
),
};
}
// Get recent news about an entity
async function getEntityNews(entityId, days = 7) {
const fromDate = new Date();
fromDate.setDate(fromDate.getDate() - days);
const { articles, total } = await client.entities.articles(entityId, {
from: fromDate.toISOString(),
limit: 20,
});
return { articles, total, period: `${days} days` };
}
// Track multiple entities
async function compareEntities(entityIds) {
const profiles = await Promise.all(
entityIds.map(async (id) => {
const { entity } = await client.entities.get(id);
const news = await getEntityNews(id);
return {
entity,
recentArticles: news.total,
};
})
);
return profiles.sort((a, b) => b.recentArticles - a.recentArticles);
}
Tutorial 4: Real-Time Alerts#
Set up real-time monitoring with webhooks.
Key Concepts#
- Creating alert subscriptions
- Configuring webhook endpoints
- Handling webhook payloads
- Managing subscription lifecycle
Creating Alerts#
javascript
import { VeritasClient } from '@veritas/b2b-sdk';
const client = new VeritasClient({ apiKey: 'sk_live_...' });
// Create keyword alert
async function createKeywordAlert(keywords) {
const { subscription } = await client.alerts.createKeywordAlert(
'My Keyword Alert',
keywords,
{
webhookUrl: 'https://your-server.com/webhook',
frequency: 'instant',
}
);
return subscription;
}
// Create entity tracking alert
async function createEntityAlert(entityIds) {
const { subscription } = await client.alerts.createEntityAlert(
'Entity Tracker',
entityIds,
{
webhookUrl: 'https://your-server.com/webhook',
frequency: 'instant',
}
);
return subscription;
}
// Create breaking news alert
async function createBreakingNewsAlert(categories) {
const { subscription } = await client.alerts.createBreakingNewsAlert(
'Breaking News',
{
categories,
webhookUrl: 'https://your-server.com/webhook',
frequency: 'instant',
}
);
return subscription;
}
Handling Webhooks (Express.js)#
javascript
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.raw({ type: 'application/json' }));
app.post('/webhook', (req, res) => {
// Verify signature
const signature = req.headers['x-veritas-signature'];
const timestamp = req.headers['x-veritas-timestamp'];
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(`${timestamp}.${req.body}`)
.digest('hex');
if (signature !== `sha256=${expected}`) {
return res.status(401).send('Invalid signature');
}
// Parse and process
const payload = JSON.parse(req.body);
switch (payload.notificationType) {
case 'keyword':
handleKeywordAlert(payload);
break;
case 'entity_mention':
handleEntityAlert(payload);
break;
case 'breaking_news':
handleBreakingNews(payload);
break;
}
res.status(200).send('OK');
});
function handleKeywordAlert(payload) {
console.log('Keyword match:', payload.payload.headline);
console.log('Keywords:', payload.payload.matchedKeywords);
}
function handleEntityAlert(payload) {
console.log('Entity mention:', payload.payload.entityName);
console.log('Article:', payload.payload.headline);
}
function handleBreakingNews(payload) {
console.log('BREAKING:', payload.payload.headline);
console.log('Category:', payload.payload.category);
}
app.listen(3000);
Tutorial 5: Media Gallery#
Build a media gallery from news articles.
Key Concepts#
- Fetching media assets
- Working with variants for responsive images
- Filtering by media type
- Getting article media
JavaScript Implementation#
javascript
import { VeritasClient } from '@veritas/b2b-sdk';
const client = new VeritasClient({ apiKey: 'sk_live_...' });
// Get images for a gallery
async function getGalleryImages(limit = 20) {
const response = await client.media.images({
role: 'featured_image',
limit,
});
return response.items.map((asset) => ({
id: asset.id,
url: client.media.getBestVariant(asset, 800),
thumbnail: client.media.getBestVariant(asset, 200),
alt: asset.altText,
caption: asset.caption,
credit: asset.credit,
}));
}
// Get media for an article
async function getArticleMedia(articleId) {
const { items } = await client.media.forArticle(articleId);
return {
featured: items.find((m) => m.role === 'featured_image'),
gallery: items.filter((m) => m.role === 'gallery'),
videos: items.filter((m) => m.kind === 'video'),
};
}
// Search for specific media
async function searchMedia(query, type = 'image') {
const results = await client.media.search({
q: query,
kind: type,
limit: 20,
});
return results.items;
}
// Build responsive image srcset
function buildSrcSet(asset) {
const widths = [320, 640, 960, 1280, 1920];
return widths
.map((w) => {
const url = client.media.getBestVariant(asset, w);
return `${url} ${w}w`;
})
.join(', ');
}
Running the Examples#
Prerequisites#
- Obtain an API key from Veritas
- Set up your environment
JavaScript#
bash
# Install the SDK
npm install @veritas/b2b-sdk
# Set your API key
export VERITAS_API_KEY=sk_live_your_api_key
# Run an example
node examples/javascript/news-aggregator.js
Python#
bash
# Install the SDK
pip install veritas-sdk
# Set your API key
export VERITAS_API_KEY=sk_live_your_api_key
# Run an example
python examples/python/news_aggregator.py
Next Steps#
- API Reference - Complete endpoint documentation
- SDKs - Full SDK documentation
- Webhooks - Webhook integration guide
- Sandbox - Testing environment