Docs
Search

Search

Powerful search capabilities for tweets, users, and hashtags with advanced filtering, operators, and location-based searches.

Overview

The Search endpoints provide comprehensive search capabilities for finding tweets based on keywords, hashtags, users, locations, and complex filter combinations. With support for advanced operators, date ranges, engagement filters, and location-based searches, you can build sophisticated search functionality into your applications.

Key Features

  • Keyword Search: Search tweets by keywords, phrases, or exact matches
  • Hashtag Search: Find tweets containing specific hashtags
  • User Filtering: Search tweets from or to specific users
  • Date Ranges: Filter tweets by creation date
  • Engagement Filters: Filter by likes, retweets, replies
  • Media Filters: Find tweets with images, videos, or links
  • Location Search: Search tweets from specific geographic locations
  • Advanced Operators: Combine multiple search criteria with boolean logic
  • Language Detection: Filter tweets by language
  • Verified Accounts: Filter to only verified accounts

Authentication

All endpoints require authentication via the X-API-KEY header:

X-API-KEY: YOUR_API_KEY

For detailed authentication information, see our Authentication Guide.


Endpoints

Search Tweets

Searches for tweets based on keywords, hashtags, and various filters. This is the most flexible search endpoint, supporting complex query combinations.

Endpoint: GET /search/tweets

Query Parameters

NameTypeRequiredDescription
qstringYesSearch query (supports operators - see below)
limitintegerNoNumber of results (Default: 20, Max: 100)
cursorstringNoPagination cursor from previous response
langstringNoLanguage code (ISO 639-1, e.g., "en", "de", "fr")
sincestringNoStart date (ISO 8601: YYYY-MM-DD)
untilstringNoEnd date (ISO 8601: YYYY-MM-DD)
fromstringNoOnly tweets from this username (without @)
tostringNoOnly tweets to this username (without @)
filterstringNoContent filter: top, latest, media, videos, images, links
verified_onlybooleanNoOnly verified accounts (Default: false)
min_repliesintegerNoMinimum number of replies
min_likesintegerNoMinimum number of likes
min_retweetsintegerNoMinimum number of retweets

Request Examples

Basic Search:

curl --request GET \
  --url 'https://<direct.gateway>/search/tweets?q=artificial%20intelligence&limit=20' \
  --header 'X-API-KEY: YOUR_API_KEY'

JavaScript:

const query = encodeURIComponent('artificial intelligence');
const response = await fetch(`https://<direct.gateway>/search/tweets?q=${query}&limit=20`, {
  headers: { 'X-API-KEY': 'YOUR_API_KEY' }
});
const data = await response.json();

Python:

import requests
 
params = {
    'q': 'artificial intelligence',
    'limit': 20,
    'lang': 'en',
    'min_likes': 100
}
response = requests.get(
    'https://<direct.gateway>/search/tweets',
    params=params,
    headers={'X-API-KEY': 'YOUR_API_KEY'}
)
data = response.json()

Complex Search with Multiple Filters:

const params = new URLSearchParams({
  q: 'AI OR machine learning',
  from: 'openai',
  since: '2024-01-01',
  until: '2024-12-31',
  filter: 'media',
  verified_only: 'true',
  min_likes: 100,
  min_retweets: 50,
  lang: 'en',
  limit: 50
});
 
const response = await fetch(`https://<direct.gateway>/search/tweets?${params}`, {
  headers: { 'X-API-KEY': 'YOUR_API_KEY' }
});

Response Example

{
  "data": [
    {
      "id": "1234567890123456789",
      "text": "This is a tweet about #API development and artificial intelligence",
      "author": {
        "id": "987654321",
        "username": "developer",
        "name": "Dev User",
        "verified": true,
        "followers_count": 15234
      },
      "created_at": "2024-10-01T12:00:00.000Z",
      "lang": "en",
      "metrics": {
        "retweet_count": 42,
        "reply_count": 15,
        "like_count": 256,
        "quote_count": 8
      },
      "entities": {
        "hashtags": ["API"],
        "urls": ["https://example.com"],
        "mentions": ["@technews"]
      },
      "media": [
        {
          "type": "photo",
          "media_url_https": "https://pbs.twimg.com/media/..."
        }
      ]
    }
  ],
  "meta": {
    "result_count": 20,
    "next_cursor": "eyJpZCI6IjEyMzQ1Njc4OTAxMjM0NTY3ODkifQ==",
    "query": "artificial intelligence"
  }
}

Common Use Cases

  1. Content Discovery: Find tweets about specific topics
  2. Trend Monitoring: Track mentions of keywords or hashtags
  3. Competitor Analysis: Monitor what's being said about competitors
  4. Sentiment Analysis: Collect tweets for sentiment analysis
  5. Influencer Research: Find influential tweets on specific topics

Performs complex searches with multiple criteria using a POST request with a structured query body. This endpoint is ideal for complex search requirements that exceed URL parameter limits.

Endpoint: POST /search/advanced

Request Body

{
  "query": {
    "keywords": ["AI", "machine learning"],
    "hashtags": ["tech", "innovation"],
    "mention": "@example_user",
    "exclude_keywords": ["spam", "advertisement"],
    "exclude_hashtags": ["ad"]
  },
  "filters": {
    "date_range": {
      "from": "2024-09-01",
      "to": "2024-10-01"
    },
    "engagement": {
      "min_likes": 100,
      "min_retweets": 50,
      "min_replies": 10
    },
    "author": {
      "verified_only": true,
      "min_followers": 1000
    },
    "content_type": {
      "has_media": true,
      "has_video": false,
      "has_links": false
    },
    "language": "en"
  },
  "sort": "engagement",
  "limit": 50
}

Request Examples

cURL:

curl --request POST \
  --url 'https://<direct.gateway>/search/advanced' \
  --header 'X-API-KEY: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "query": {
      "keywords": ["AI", "machine learning"],
      "hashtags": ["tech"]
    },
    "filters": {
      "engagement": {
        "min_likes": 100
      }
    },
    "limit": 50
  }'

JavaScript:

const response = await fetch('https://<direct.gateway>/search/advanced', {
  method: 'POST',
  headers: {
    'X-API-KEY': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query: {
      keywords: ['AI', 'machine learning'],
      hashtags: ['tech', 'innovation'],
      exclude_keywords: ['spam']
    },
    filters: {
      date_range: {
        from: '2024-09-01',
        to: '2024-10-01'
      },
      engagement: {
        min_likes: 100,
        min_retweets: 50
      },
      author: {
        verified_only: true,
        min_followers: 1000
      }
    },
    sort: 'engagement',
    limit: 50
  })
});
const data = await response.json();

Python:

import requests
 
payload = {
    "query": {
        "keywords": ["AI", "machine learning"],
        "hashtags": ["tech"],
        "exclude_keywords": ["spam"]
    },
    "filters": {
        "engagement": {
            "min_likes": 100
        },
        "author": {
            "verified_only": True
        }
    },
    "limit": 50
}
 
response = requests.post(
    'https://<direct.gateway>/search/advanced',
    json=payload,
    headers={'X-API-KEY': 'YOUR_API_KEY'}
)
data = response.json()

Response Format

Same as basic search endpoint, but may include additional metadata about the search query complexity.

  • Complex Queries: When your query exceeds URL length limits
  • Multiple Exclusions: When you need to exclude many terms
  • Structured Filters: When you prefer structured filter objects
  • Programmatic Building: When building queries programmatically

Search by Hashtag

Searches for tweets containing a specific hashtag. This is optimized for hashtag searches and includes hashtag statistics.

Endpoint: GET /search/hashtag/{hashtag}

Path Parameters

NameTypeRequiredDescription
hashtagstringYesThe hashtag without the # symbol (e.g., "API" not "#API")

Query Parameters

NameTypeRequiredDescription
limitintegerNoNumber of results (Default: 20, Max: 100)
filterstringNoSort filter: top (most popular) or latest (most recent) - Default: latest
cursorstringNoPagination cursor

Request Examples

# Latest tweets with hashtag
curl --request GET \
  --url 'https://<direct.gateway>/search/hashtag/API?limit=20&filter=latest' \
  --header 'X-API-KEY: YOUR_API_KEY'
 
# Top tweets with hashtag
curl --request GET \
  --url 'https://<direct.gateway>/search/hashtag/API?limit=20&filter=top' \
  --header 'X-API-KEY: YOUR_API_KEY'

JavaScript:

const hashtag = 'API';
const response = await fetch(
  `https://<direct.gateway>/search/hashtag/${hashtag}?limit=20&filter=top`,
  { headers: { 'X-API-KEY': 'YOUR_API_KEY' } }
);
const data = await response.json();

Response Example

{
  "hashtag": "API",
  "data": [
    {
      "id": "1234567890123456789",
      "text": "Great tutorial on REST API design #API",
      "author": {
        "username": "dev_example",
        "verified": false
      },
      "created_at": "2024-10-01T12:00:00.000Z",
      "metrics": {
        "like_count": 523,
        "retweet_count": 87
      }
    }
  ],
  "meta": {
    "result_count": 20,
    "hashtag_stats": {
      "total_tweets_24h": 15420,
      "trending_score": 8.7,
      "peak_hour": "2024-10-01T14:00:00.000Z"
    },
    "next_cursor": "..."
  }
}

Use Cases

  • Hashtag Tracking: Monitor specific hashtags
  • Trend Analysis: Analyze hashtag popularity
  • Campaign Monitoring: Track campaign hashtags
  • Community Discovery: Find communities around hashtags

Search by Location

Searches for tweets from a specific geographic location. Useful for local content discovery and location-based analytics.

Endpoint: GET /search/location

Query Parameters

NameTypeRequiredDescription
qstringYesSearch term
latitudefloatYesLatitude coordinate (-90 to 90)
longitudefloatYesLongitude coordinate (-180 to 180)
radiusstringNoSearch radius (e.g., "10km", "5mi", "1000m") - Default: 10km
limitintegerNoNumber of results (Default: 20, Max: 100)
cursorstringNoPagination cursor

Request Examples

# Search near San Francisco
curl --request GET \
  --url 'https://<direct.gateway>/search/location?q=coffee&latitude=37.7749&longitude=-122.4194&radius=5km&limit=20' \
  --header 'X-API-KEY: YOUR_API_KEY'

JavaScript:

const params = new URLSearchParams({
  q: 'coffee',
  latitude: 37.7749,
  longitude: -122.4194,
  radius: '5km',
  limit: 20
});
 
const response = await fetch(
  `https://<direct.gateway>/search/location?${params}`,
  { headers: { 'X-API-KEY': 'YOUR_API_KEY' } }
);

Python:

import requests
 
params = {
    'q': 'coffee',
    'latitude': 37.7749,
    'longitude': -122.4194,
    'radius': '5km',
    'limit': 20
}
 
response = requests.get(
    'https://<direct.gateway>/search/location',
    params=params,
    headers={'X-API-KEY': 'YOUR_API_KEY'}
)

Response Example

{
  "data": [
    {
      "id": "1234567890123456789",
      "text": "Best coffee shop in SF!",
      "author": {
        "username": "coffee_lover",
        "name": "Coffee Lover"
      },
      "created_at": "2024-10-01T12:00:00.000Z",
      "geo": {
        "place_id": "abc123",
        "full_name": "San Francisco, CA",
        "coordinates": {
          "lat": 37.7749,
          "lon": -122.4194
        }
      }
    }
  ],
  "meta": {
    "result_count": 15,
    "search_location": {
      "lat": 37.7749,
      "lon": -122.4194,
      "radius": "5km"
    }
  }
}

Radius Formats

  • "10km" - 10 kilometers
  • "5mi" - 5 miles
  • "1000m" - 1000 meters
  • Maximum radius: 25km (15.5 miles)

Use Cases

  • Local Business Discovery: Find local mentions
  • Event Monitoring: Track location-based events
  • Geographic Analytics: Analyze regional trends
  • Local News: Find local news and updates

Search Query Operators

The search query parameter (q) supports powerful operators for building complex searches. These operators can be combined to create sophisticated queries.

Basic Operators

OperatorSyntaxExampleDescription
Exact Phrase"phrase""machine learning"Matches exact phrase
OROR (uppercase)AI OR MLMatches either term
ANDAND (uppercase)AI AND MLMatches both terms
Exclude-keywordAI -spamExcludes keyword
Hashtag#hashtag#techMatches hashtag
Mention@username@elonmuskMatches mention

User Operators

OperatorSyntaxExampleDescription
From Userfrom:usernamefrom:elonmuskTweets from user
To Userto:usernameto:supportTweets to user
Mentioning@username@techcrunchTweets mentioning user

Date Operators

OperatorSyntaxExampleDescription
Sincesince:YYYY-MM-DDsince:2024-01-01From date onwards
Untiluntil:YYYY-MM-DDuntil:2024-12-31Up to date

Content Filters

OperatorSyntaxExampleDescription
Mediafilter:mediaAI filter:mediaTweets with media
Videosfilter:videostutorial filter:videosTweets with videos
Imagesfilter:imagesart filter:imagesTweets with images
Linksfilter:linksnews filter:linksTweets with links
Verifiedfilter:verifiedtech filter:verifiedFrom verified accounts

Engagement Filters

OperatorSyntaxExampleDescription
Min Likesmin_likes:NAI min_likes:100Minimum likes (use query param)
Min Retweetsmin_retweets:Nnews min_retweets:50Minimum retweets (use query param)

Complex Query Examples

Example 1: Technology News from Verified Accounts

"artificial intelligence" OR "machine learning" 
filter:verified 
filter:links 
since:2024-01-01 
min_likes:100

JavaScript:

const query = '"artificial intelligence" OR "machine learning" filter:verified filter:links since:2024-01-01';
const params = new URLSearchParams({
  q: query,
  min_likes: 100,
  limit: 50
});

Example 2: Hashtag Search Excluding Spam

#bitcoin OR #crypto -spam -advertisement 
filter:media 
min_retweets:50

Example 3: User-Specific Search with Date Range

from:openai 
("GPT" OR "ChatGPT") 
since:2024-01-01 
until:2024-12-31 
filter:videos

Example 4: Location-Based Tech Discussion

"tech meetup" OR "developer event" 
filter:media 
min_likes:10
("AI" OR "artificial intelligence") 
AND ("tutorial" OR "guide") 
-filter:spam 
from:verified_accounts 
since:2024-06-01 
filter:links

Operator Precedence

Operators are evaluated in this order:

  1. Parentheses () - Grouping
  2. AND - Logical AND
  3. OR - Logical OR
  4. - - Exclusion

Example:

(AI OR ML) AND tutorial -spam

This searches for tweets containing (AI OR ML) AND tutorial, excluding spam.


Best Practices

Search-Specific Tips

  • Keep queries focused: Specific queries yield better results than broad ones
  • Use date ranges: Limit date ranges to improve relevance and performance
  • Combine filters: Use multiple filters to narrow results effectively
  • Cache popular queries: Search results can be cached for 5-10 minutes
  • Use advanced search: For complex queries, use POST /search/advanced endpoint

For general API best practices including error handling, rate limits, and performance optimization, see our Best Practices Guide.


For comprehensive error handling and rate limits information, see our guides:

Troubleshooting

IssueSymptomsPossible CausesSolutions
No results for valid queryQuery looks correct but returns no resultsQuery too specific, date range too narrow, filters too restrictive, no matching tweets existBroaden search terms, expand date range, remove some filters, check if tweets exist manually on Twitter
Inconsistent resultsSame query returns different resultsTweets being deleted, real-time index updates, rate limiting affecting resultsThis is normal behavior - Twitter's index updates in real-time. Cache results if consistency is needed, use specific date ranges for historical searches
Query performanceSlow search responsesComplex queries, large date ranges, too many filtersSimplify query structure, narrow date ranges, use pagination instead of large limits, consider using advanced search endpoint

FAQ

Search typically covers tweets from the past 7-30 days, depending on the query and filters. For older tweets, use specific date ranges, but availability decreases with age.

Can I search for deleted tweets?

No, deleted tweets are removed from search results immediately.

What's the difference between filter:top and filter:latest?

  • filter:top: Returns most popular/engaging tweets
  • filter:latest: Returns most recent tweets first

Can I search for tweets in multiple languages?

Yes, but you can only specify one language per query using the lang parameter. For multiple languages, make separate requests.

How do I search for tweets with specific media types?

Use content filters:

  • filter:media - Any media
  • filter:videos - Videos only
  • filter:images - Images only
  • filter:links - Tweets with links

Can I combine multiple hashtags?

Yes, use OR operator: #hashtag1 OR #hashtag2 or search for tweets containing both: #hashtag1 #hashtag2

Location accuracy depends on whether users have location enabled and the precision of their location data. Not all tweets have location information.