Overview
The Twitter API (now X API) provides developers with programmatic access to Twitter data. You can use it to search for tweets, retrieve user profiles, post tweets, analyze trends, and more. The API is essential for building applications that integrate with the Twitter platform.
Integration Guide
Step 1: Apply for API Access
To use the Twitter API, you need to apply for access through the Twitter Developer Portal.
- Go to the Twitter Developer Portal
- Sign in with your Twitter account
- Apply for a developer account by describing your use case
- Once approved, create a project and an app within that project
- Generate the necessary API keys and tokens
Important Note
Step 2: Authentication
Twitter API v2 supports several authentication methods:
- OAuth 2.0 Authorization Code with PKCE: For user-context requests (acting on behalf of a user)
- OAuth 1.0a: Legacy authentication still supported for user-context requests
- App-only Bearer Token: For app-context requests (not on behalf of a user)
For this example, we'll use the App-only Bearer Token authentication, which is simpler for read-only operations.
Step 3: Set Up Your Project
Create the necessary files for your Twitter API integration:
- index.html - The HTML structure
- styles.css - CSS for styling
- twitter-api.js - JavaScript for API integration
Step 4: Implement the Code
Copy the following code into your project files:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Twitter API Demo</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<header>
<h1>Twitter Explorer</h1>
</header>
<div class="search-section">
<h2>Search Tweets</h2>
<div class="search-container">
<input type="text" id="search-input" placeholder="Enter search query...">
<button id="search-btn" class="btn primary-btn">Search</button>
</div>
<div class="search-options">
<label>
<input type="checkbox" id="include-images" checked>
Include images
</label>
<label>
<input type="checkbox" id="include-metrics" checked>
Include metrics
</label>
<label>
<input type="number" id="max-results" min="10" max="100" value="20">
Max results
</label>
</div>
</div>
<div class="user-lookup-section">
<h2>User Lookup</h2>
<div class="search-container">
<input type="text" id="username-input" placeholder="Enter username (without @)">
<button id="user-lookup-btn" class="btn primary-btn">Look Up</button>
</div>
</div>
<div id="results-container" class="results-container">
<!-- Results will be displayed here -->
</div>
<div id="user-profile" class="user-profile">
<!-- User profile will be displayed here -->
</div>
<div id="user-tweets" class="tweets-container">
<!-- User tweets will be displayed here -->
</div>
</div>
<script src="twitter-api.js"></script>
</body>
</html>Step 5: Replace the Bearer Token
Replace YOUR_BEARER_TOKEN in the JavaScript file with your actual Bearer Token from the Twitter Developer Portal.
Security Note
Step 6: Test Your Implementation
Open your HTML file in a browser to test your Twitter API integration. You should be able to:
- Search for tweets using keywords
- Look up user profiles by username
- View a user's recent tweets
- See tweet metrics and media
Error Handling
Common Errors
- 401 Unauthorized: Invalid or expired credentials
- 403 Forbidden: Valid credentials but insufficient permissions
- 404 Not Found: The requested resource doesn't exist
- 429 Too Many Requests: Rate limit exceeded
- 503 Service Unavailable: Twitter is temporarily unavailable
Rate Limiting
Twitter API has rate limits that vary by endpoint and access level. The API returns rate limit information in response headers:
x-rate-limit-limit: The rate limit ceiling for that endpointx-rate-limit-remaining: The number of requests left for the time windowx-rate-limit-reset: The time at which the rate limit resets, in epoch seconds
Best Practice
Error Response Format
When an error occurs, the Twitter API returns a JSON response with error details:
{
"errors": [
{
"title": "Invalid Request",
"detail": "One or more parameters to your request was invalid.",
"type": "https://api.twitter.com/2/problems/invalid-request",
"parameter": "query",
"value": ""
}
]
}Your error handling should check for this structure and extract meaningful information to display to users or log for debugging.
API Details
- Base URL
https://api.twitter.com/2- Authentication
- OAuth 1.0a / OAuth 2.0 / Bearer Token
- Documentation
- Official Docs
Endpoints
- GET
/tweets/{id}Returns a variety of information about a single Tweet specified by the requested ID
Parameters
id*string - The unique identifier of the Tweetexpansionsstring - Comma-separated list of fields to expand (e.g., author_id,attachments.media_keys)tweet.fieldsstring - Comma-separated list of Tweet fields to include (e.g., created_at,public_metrics)user.fieldsstring - Comma-separated list of User fields to include (e.g., name,username,profile_image_url)media.fieldsstring - Comma-separated list of Media fields to include (e.g., preview_image_url,type)
- GET
/users/{id}Returns information about a user specified by the requested ID
Parameters
id*string - The unique identifier of the Userexpansionsstring - Comma-separated list of fields to expand (e.g., pinned_tweet_id)user.fieldsstring - Comma-separated list of User fields to include (e.g., created_at,description,public_metrics)tweet.fieldsstring - Comma-separated list of Tweet fields to include (e.g., created_at,text)
- GET
/tweets/search/recentSearch for Tweets published in the last 7 days
Parameters
query*string - One query for matching Tweets (512 characters max)max_resultsinteger - The maximum number of results to return (10-100, default: 10)expansionsstring - Comma-separated list of fields to expandtweet.fieldsstring - Comma-separated list of Tweet fields to includeuser.fieldsstring - Comma-separated list of User fields to includemedia.fieldsstring - Comma-separated list of Media fields to includeplace.fieldsstring - Comma-separated list of Place fields to includepoll.fieldsstring - Comma-separated list of Poll fields to include
- GET
/users/{id}/tweetsReturns Tweets composed by a single user, specified by the requested user ID
Parameters
id*string - The unique identifier of the Usermax_resultsinteger - The maximum number of results to return (5-100, default: 10)excludestring - Comma-separated list of the types of Tweets to exclude (e.g., retweets,replies)expansionsstring - Comma-separated list of fields to expandtweet.fieldsstring - Comma-separated list of Tweet fields to includeuser.fieldsstring - Comma-separated list of User fields to include
- POST
/tweetsCreates a Tweet on behalf of an authenticated user
Parameters
text*string - The text of the Tweet (max 280 characters)replyobject - Object containing information for a reply Tweetquote_tweet_idstring - Link to the Tweet being quotedpollobject - Object containing poll optionsmediaobject - Object containing media information