Usage Examples
Real-world usage examples and integrations with popular tools like N8N, Zapier, and custom applications.
Overview
This guide provides practical examples of how to use the Twitter API in real-world scenarios, including integrations with automation tools, custom applications, and common use cases.
Automation Tools
N8N Integration
N8N is a powerful workflow automation tool. Here's how to integrate the Twitter API:
Setup
-
Create HTTP Request Node
- Add an "HTTP Request" node to your workflow
- Set method to
GETorPOSTas needed
-
Configure Authentication
- Add header:
X-API-KEYwith your API key - Set URL to your gateway endpoint
- Add header:
Example: Monitor User Tweets
{
"method": "GET",
"url": "https://<direct.gateway>/user/by/username/elonmusk/tweets",
"headers": {
"X-API-KEY": "{{ $env.API_KEY }}"
},
"qs": {
"count": 10
}
}Example: Search Tweets Workflow
- Trigger: Schedule node (runs every hour)
- HTTP Request: Search for tweets
{ "method": "GET", "url": "https://<direct.gateway>/search/tweets", "headers": { "X-API-KEY": "{{ $env.API_KEY }}" }, "qs": { "q": "artificial intelligence", "limit": 20, "min_likes": 100 } } - Process Results: Filter and process tweets
- Send Notifications: Send to Slack, email, etc.
Example: Real-Time Tweet Monitoring
- Webhook Trigger: Receive webhook from external service
- Get Tweet: Fetch tweet details
{ "method": "GET", "url": "https://<direct.gateway>/tweet/{{ $json.tweetId }}", "headers": { "X-API-KEY": "{{ $env.API_KEY }}" } } - Analyze: Extract data, check metrics
- Action: Send to database, trigger other workflows
Zapier Integration
Zapier provides a simpler interface for non-technical users:
Setup Steps
-
Create Zap
- Choose trigger (Schedule, Webhook, etc.)
- Add "Code by Zapier" or "Webhooks by Zapier"
-
Configure API Call
// In Code by Zapier const response = await fetch('https://<direct.gateway>/user/by/username/elonmusk', { headers: { 'X-API-KEY': inputData.apiKey } }); return await response.json(); -
Process Results
- Map response data to next steps
- Filter or transform data as needed
Make (Integromat) Integration
Make.com offers visual workflow automation:
HTTP Module Configuration
- Method: GET/POST
- URL: Your API endpoint
- Headers:
X-API-KEY: {{your_api_key}} - Query Parameters: Set as needed
Example Workflow
- Trigger: Schedule module (every 15 minutes)
- HTTP Request: Get trending topics
- Data Store: Save to Google Sheets
- Notification: Send email if new trends detected
Custom Applications
React Application
Example: Tweet Search Component
import { useState } from 'react';
function TweetSearch() {
const [query, setQuery] = useState('');
const [tweets, setTweets] = useState([]);
const [loading, setLoading] = useState(false);
const searchTweets = async () => {
setLoading(true);
try {
const response = await fetch(
`https://<direct.gateway>/search/tweets?q=${encodeURIComponent(query)}&limit=20`,
{
headers: {
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY
}
}
);
const data = await response.json();
setTweets(data.data || []);
} catch (error) {
console.error('Search failed:', error);
} finally {
setLoading(false);
}
};
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search tweets..."
/>
<button onClick={searchTweets} disabled={loading}>
{loading ? 'Searching...' : 'Search'}
</button>
<div>
{tweets.map(tweet => (
<div key={tweet.id}>
<p>{tweet.text}</p>
<small>Likes: {tweet.metrics?.like_count || 0}</small>
</div>
))}
</div>
</div>
);
}Node.js Backend Service
Example: Tweet Monitoring Service
const express = require('express');
const axios = require('axios');
const app = express();
const API_KEY = process.env.API_KEY;
const BASE_URL = 'https://<direct.gateway>';
// Monitor user tweets
async function monitorUserTweets(username) {
try {
const response = await axios.get(
`${BASE_URL}/user/by/username/${username}/tweets`,
{
headers: { 'X-API-KEY': API_KEY },
params: { count: 10 }
}
);
return response.data;
} catch (error) {
console.error('Error fetching tweets:', error.message);
throw error;
}
}
// API endpoint
app.get('/api/user/:username/tweets', async (req, res) => {
try {
const tweets = await monitorUserTweets(req.params.username);
res.json(tweets);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch tweets' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Python Data Analysis
Example: Analyze Trending Topics
import requests
import pandas as pd
from datetime import datetime
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://<direct.gateway>"
def get_trending_topics(woeid=1):
"""Get trending topics for a location"""
response = requests.get(
f"{BASE_URL}/trends/topics",
headers={"X-API-KEY": API_KEY},
params={"woeid": woeid, "limit": 50}
)
return response.json()
def analyze_trends():
"""Analyze and store trending topics"""
trends = get_trending_topics()
# Convert to DataFrame
df = pd.DataFrame(trends['data'])
# Add timestamp
df['fetched_at'] = datetime.now()
# Save to CSV
df.to_csv(f"trends_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", index=False)
# Print summary
print(f"Found {len(df)} trending topics")
print(f"Top 5: {df.head()['name'].tolist()}")
return df
# Run analysis
if __name__ == "__main__":
analyze_trends()Common Use Cases
1. Social Media Monitoring
Monitor brand mentions and competitors:
async function monitorBrandMentions(brandName) {
const response = await fetch(
`https://<direct.gateway>/search/tweets?q=${encodeURIComponent(brandName)}&limit=100`,
{
headers: { 'X-API-KEY': API_KEY }
}
);
const data = await response.json();
// Analyze sentiment, engagement, etc.
return data.data.map(tweet => ({
id: tweet.id,
text: tweet.text,
author: tweet.author.username,
engagement: tweet.metrics.like_count + tweet.metrics.retweet_count,
timestamp: tweet.created_at
}));
}2. Content Aggregation
Aggregate tweets from multiple users:
async function aggregateUserTweets(usernames) {
const allTweets = [];
for (const username of usernames) {
const response = await fetch(
`https://<direct.gateway>/user/by/username/${username}/tweets?limit=20`,
{
headers: { 'X-API-KEY': API_KEY }
}
);
const data = await response.json();
allTweets.push(...data.data);
}
// Sort by engagement
return allTweets.sort((a, b) =>
(b.metrics.like_count + b.metrics.retweet_count) -
(a.metrics.like_count + a.metrics.retweet_count)
);
}3. Analytics Dashboard
Build a real-time analytics dashboard:
async function getAnalyticsData(userId) {
const [user, tweets, analytics] = await Promise.all([
fetch(`https://<direct.gateway>/user/${userId}`, {
headers: { 'X-API-KEY': API_KEY }
}).then(r => r.json()),
fetch(`https://<direct.gateway>/user/${userId}/tweets?limit=100`, {
headers: { 'X-API-KEY': API_KEY }
}).then(r => r.json()),
fetch(`https://<direct.gateway>/analytics/user/${userId}?timeframe=30d`, {
headers: { 'X-API-KEY': API_KEY }
}).then(r => r.json())
]);
return {
user: user.data,
recentTweets: tweets.data,
analytics: analytics.data
};
}4. Automated Reporting
Generate daily reports:
import requests
from datetime import datetime, timedelta
def generate_daily_report(hashtag):
"""Generate daily report for a hashtag"""
# Get hashtag analytics
response = requests.get(
f"https://<direct.gateway>/trends/hashtag/{hashtag}/analytics",
headers={"X-API-KEY": API_KEY},
params={"timeframe": "24h"}
)
analytics = response.json()
# Generate report
report = f"""
Daily Report for #{hashtag}
===========================
Date: {datetime.now().strftime('%Y-%m-%d')}
Total Tweets: {analytics['analytics']['total_tweets']}
Unique Authors: {analytics['analytics']['unique_authors']}
Engagement Rate: {analytics['analytics']['engagement_rate']}%
Sentiment:
- Positive: {analytics['analytics']['sentiment']['positive']}%
- Neutral: {analytics['analytics']['sentiment']['neutral']}%
- Negative: {analytics['analytics']['sentiment']['negative']}%
"""
return report
# Send report via email or save to file
report = generate_daily_report("AI")
print(report)5. Real-Time Alerts
Set up alerts for specific conditions:
async function checkAndAlert(conditions) {
// Check trending topics
const trends = await fetch(
'https://<direct.gateway>/trends/topics?woeid=1',
{ headers: { 'X-API-KEY': API_KEY } }
).then(r => r.json());
// Check conditions
const alerts = [];
for (const trend of trends.data) {
if (conditions.some(cond =>
trend.name.toLowerCase().includes(cond.keyword.toLowerCase()) &&
trend.tweet_volume > cond.minVolume
)) {
alerts.push({
trend: trend.name,
volume: trend.tweet_volume,
url: trend.url
});
}
}
// Send alerts
if (alerts.length > 0) {
await sendNotification(alerts);
}
return alerts;
}Integration Patterns
Webhook Integration
Receive real-time updates via webhooks:
// Express.js webhook endpoint
app.post('/webhook/tweet', async (req, res) => {
const { tweetId } = req.body;
// Fetch tweet details
const tweet = await fetch(
`https://<direct.gateway>/tweet/${tweetId}`,
{ headers: { 'X-API-KEY': API_KEY } }
).then(r => r.json());
// Process tweet
await processTweet(tweet);
res.json({ success: true });
});Database Integration
Store tweets in database:
import requests
import sqlite3
def store_tweets_in_db(query, limit=100):
"""Search and store tweets in database"""
response = requests.get(
"https://<direct.gateway>/search/tweets",
headers={"X-API-KEY": API_KEY},
params={"q": query, "limit": limit}
)
tweets = response.json()['data']
# Store in database
conn = sqlite3.connect('tweets.db')
cursor = conn.cursor()
for tweet in tweets:
cursor.execute('''
INSERT INTO tweets (id, text, author, created_at, likes, retweets)
VALUES (?, ?, ?, ?, ?, ?)
''', (
tweet['id'],
tweet['text'],
tweet['author']['username'],
tweet['created_at'],
tweet['metrics']['like_count'],
tweet['metrics']['retweet_count']
))
conn.commit()
conn.close()
return len(tweets)Best Practices for Integrations
1. Error Handling
Always implement proper error handling:
async function safeAPIRequest(url, options) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
// Implement retry logic or fallback
throw error;
}
}2. Rate Limit Management
Respect rate limits in your integrations:
class RateLimitedQueue {
constructor(requestsPerSecond = 5) {
this.queue = [];
this.interval = 1000 / requestsPerSecond;
}
async add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.process();
});
}
async process() {
if (this.queue.length === 0) return;
const { requestFn, resolve, reject } = this.queue.shift();
try {
const result = await requestFn();
resolve(result);
} catch (error) {
reject(error);
}
setTimeout(() => this.process(), this.interval);
}
}3. Caching
Cache responses to reduce API calls:
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
async function getCached(url) {
const cached = cache.get(url);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const data = await fetch(url, {
headers: { 'X-API-KEY': API_KEY }
}).then(r => r.json());
cache.set(url, { data, timestamp: Date.now() });
return data;
}Related Documentation
- Getting Started - Initial setup guide
- Authentication Guide - API key setup
- Error Handling Guide - Error handling
- Rate Limits Guide - Rate limit management
- Best Practices - API best practices
