Twitter/X Tweets API

Access Twitter/X user tweets with advanced AI-powered search functionality, engagement metrics, and media content analysis.

Overview

The Tweets API allows you to retrieve structured Twitter/X user data and tweets with support for multiple X handles, customizable date ranges, and detailed engagement analytics. This endpoint leverages AI-powered processing to provide enhanced search capabilities and comprehensive tweet analysis.
This API may have higher latency due to AI-powered processing for enhanced data quality and analysis.

Endpoint

GET /api/tweets

Authentication

All requests require a valid API key in the Authorization header:
Authorization: Bearer your-api-key

Query Parameters

ParameterTypeRequiredDescriptionExample
xhandlesstringYesComma-separated list of X handles (without @ symbol, max 3)"elonmusk,dhh,tim_cook"
fromDatestringNoStart date for search data in YYYY-MM-DD format"2025-01-15"
toDatestringNoEnd date for search data in YYYY-MM-DD format"2025-01-16"
maxResultsnumberNoMaximum number of tweets to return (max 50, default: 10)20
maxSearchResultsnumberNoMaximum number of search results to consider (max 50, default: 20)30

Example Requests

Basic Request

Get recent tweets from a single user:
curl -X GET "https://api.fcontext.com/api/tweets?xhandles=dhh&maxResults=5" \
  -H "Authorization: Bearer your-api-key"

Multiple Users with Date Range

Get tweets from multiple users within a specific date range:
curl -X GET "https://api.fcontext.com/api/tweets?xhandles=elonmusk,dhh&fromDate=2025-01-15&toDate=2025-01-16&maxResults=20" \
  -H "Authorization: Bearer your-api-key"
Get comprehensive tweet data with maximum search results:
curl -X GET "https://api.fcontext.com/api/tweets?xhandles=tim_cook&maxResults=30&maxSearchResults=50" \
  -H "Authorization: Bearer your-api-key"

Response Format

Success Response (200)

{
  "success": true,
  "data": {
    "user": "dhh",
    "fromDate": "2025-01-16",
    "toDate": "2025-01-16",
    "total_tweets": 3,
    "tweets": [
      {
        "id": "1234567890123456789",
        "timestamp": "2025-01-16T10:30:00Z",
        "content": "Just shipped a new feature for Rails 8.0! The developer experience keeps getting better. #Rails #WebDev",
        "engagement": {
          "likes": 245,
          "reposts": 67,
          "quotes": 12,
          "replies": 34,
          "bookmarks": 89,
          "views": 5420
        },
        "media": {
          "type": "photo",
          "url": "https://pbs.twimg.com/media/example.jpg"
        },
        "quoted_post": null
      },
      {
        "id": "1234567890123456790",
        "timestamp": "2025-01-16T08:15:00Z",
        "content": "Working on some exciting database optimizations. Performance improvements are always satisfying to implement.",
        "engagement": {
          "likes": 156,
          "reposts": 23,
          "quotes": 5,
          "replies": 18,
          "bookmarks": 45,
          "views": 2890
        },
        "media": null,
        "quoted_post": "Previous discussion about database scaling strategies..."
      }
    ]
  },
  "message": "Twitter/X user data and tweets retrieved successfully",
  "timestamp": "2025-01-16T10:30:00.000Z",
  "meta": {
    "pagination": {
      "currentPage": 1,
      "pageSize": 3,
      "totalItems": 3,
      "totalPages": 1,
      "hasMore": false
    }
  }
}

Response Fields

Tweet Object

FieldTypeDescription
idstringUnique tweet identifier
timestampstringTweet publication timestamp in GMT format
contentstringMain text content of the tweet
engagementobjectEngagement metrics for the tweet
mediaobject/nullMedia attachments, null if no media
quoted_poststring/nullReferenced quoted tweet content if applicable

Engagement Object

FieldTypeDescription
likesnumberNumber of likes on the tweet
repostsnumberNumber of reposts/retweets
quotesnumberNumber of quote tweets
repliesnumberNumber of replies
bookmarksnumberNumber of bookmarks
viewsnumberNumber of views

Media Object

FieldTypeDescription
typestringType of media content (photo, video, gif)
urlstringURL of the media file

Error Responses

400 Bad Request

Invalid request parameters:
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": {
      "field": "xhandles",
      "issue": "At least one X handle is required",
      "received": "",
      "expected": "Non-empty string (e.g., \"elonmusk,dhh\")"
    }
  },
  "timestamp": "2025-01-16T10:30:00.000Z"
}

401 Unauthorized

Invalid or missing API key:
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key",
    "details": {
      "hint": "Please provide a valid API key in the Authorization header"
    }
  },
  "timestamp": "2025-01-16T10:30:00.000Z"
}

429 Rate Limit Exceeded

Too many requests:
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please try again later.",
    "details": {
      "limit": 100,
      "remaining": 0,
      "resetTime": "2025-01-16T11:00:00.000Z"
    }
  },
  "timestamp": "2025-01-16T10:30:00.000Z"
}

503 Service Unavailable

External service temporarily unavailable:
{
  "success": false,
  "error": {
    "code": "SERVICE_UNAVAILABLE",
    "message": "Twitter/X API service is temporarily unavailable",
    "details": {
      "service": "Twitter API",
      "estimatedRecovery": "2025-01-16T11:30:00.000Z"
    }
  },
  "timestamp": "2025-01-16T10:30:00.000Z"
}

Rate Limits

  • Requests per minute: 100
  • Requests per hour: 1,000
  • Daily requests: 10,000
Rate limits are applied per API key. When you exceed the rate limit, you’ll receive a 429 status code with details about when you can make requests again.

Best Practices

1. Handle Rate Limits

Implement exponential backoff when receiving 429 responses:
async function fetchTweets(xhandles, retries = 3) {
  try {
    const response = await fetch(`/api/tweets?xhandles=${xhandles}`, {
      headers: { 'Authorization': 'Bearer your-api-key' }
    });
    
    if (response.status === 429 && retries > 0) {
      const retryAfter = response.headers.get('Retry-After') || 60;
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      return fetchTweets(xhandles, retries - 1);
    }
    
    return response.json();
  } catch (error) {
    console.error('Error fetching tweets:', error);
    throw error;
  }
}

2. Optimize Date Ranges

Use specific date ranges to get more targeted results and reduce processing time:
# Good: Specific date range
curl "https://api.fcontext.com/api/tweets?xhandles=dhh&fromDate=2025-01-15&toDate=2025-01-16"

# Less optimal: No date range (returns recent tweets)
curl "https://api.fcontext.com/api/tweets?xhandles=dhh"

3. Batch Multiple Users

Request multiple users in a single call when possible:
# Efficient: Multiple users in one request
curl "https://api.fcontext.com/api/tweets?xhandles=elonmusk,dhh,tim_cook"

# Less efficient: Separate requests for each user
curl "https://api.fcontext.com/api/tweets?xhandles=elonmusk"
curl "https://api.fcontext.com/api/tweets?xhandles=dhh"
curl "https://api.fcontext.com/api/tweets?xhandles=tim_cook"

4. Handle Media Content

Check for media attachments and handle different media types:
function processTweet(tweet) {
  console.log(`Tweet: ${tweet.content}`);
  
  if (tweet.media) {
    console.log(`Media: ${tweet.media.type} - ${tweet.media.url}`);
    
    // Handle different media types
    switch (tweet.media.type) {
      case 'photo':
        // Process image
        break;
      case 'video':
        // Process video
        break;
      case 'gif':
        // Process GIF
        break;
    }
  }
  
  // Process engagement metrics
  const engagement = tweet.engagement;
  console.log(`Engagement: ${engagement.likes} likes, ${engagement.reposts} reposts`);
}

Use Cases

1. Social Media Monitoring

Monitor key influencers and thought leaders in your industry:
curl "https://api.fcontext.com/api/tweets?xhandles=elonmusk,sundarpichai,satyanadella&maxResults=50"

2. Sentiment Analysis

Combine with sentiment analysis tools to gauge market sentiment:
async function analyzeSentiment(xhandles) {
  const tweets = await fetchTweets(xhandles);
  
  for (const tweet of tweets.data.tweets) {
    const sentiment = await analyzeTweetSentiment(tweet.content);
    console.log(`Tweet: ${tweet.content.substring(0, 50)}...`);
    console.log(`Sentiment: ${sentiment.label} (${sentiment.score})`);
  }
}

3. Content Research

Research trending topics and engagement patterns:
curl "https://api.fcontext.com/api/tweets?xhandles=techcrunch,verge,wired&fromDate=2025-01-15&maxResults=30"

SDKs and Libraries

JavaScript/Node.js

import { FinancialContextAPI } from '@financialcontext/sdk';

const api = new FinancialContextAPI('your-api-key');

const tweets = await api.tweets.get({
  xhandles: 'dhh,elonmusk',
  maxResults: 20,
  fromDate: '2025-01-15'
});

Python

from financialcontext import FinancialContextAPI

api = FinancialContextAPI('your-api-key')

tweets = api.tweets.get(
    xhandles='dhh,elonmusk',
    max_results=20,
    from_date='2025-01-15'
)

Support

For additional support or questions about the Tweets API:
The Twitter/X Tweets API is designed to provide comprehensive social media data for financial and market analysis. Always ensure compliance with Twitter’s Terms of Service and applicable data privacy regulations when using this data.