Twitter API (X)

Social Media
Intermediate

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.

  1. Go to the Twitter Developer Portal
  2. Sign in with your Twitter account
  3. Apply for a developer account by describing your use case
  4. Once approved, create a project and an app within that project
  5. Generate the necessary API keys and tokens

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.

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 endpoint
  • x-rate-limit-remaining: The number of requests left for the time window
  • x-rate-limit-reset: The time at which the rate limit resets, in epoch seconds

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 Tweet
    • expansions
      string - Comma-separated list of fields to expand (e.g., author_id,attachments.media_keys)
    • tweet.fields
      string - Comma-separated list of Tweet fields to include (e.g., created_at,public_metrics)
    • user.fields
      string - Comma-separated list of User fields to include (e.g., name,username,profile_image_url)
    • media.fields
      string - 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 User
    • expansions
      string - Comma-separated list of fields to expand (e.g., pinned_tweet_id)
    • user.fields
      string - Comma-separated list of User fields to include (e.g., created_at,description,public_metrics)
    • tweet.fields
      string - Comma-separated list of Tweet fields to include (e.g., created_at,text)
  • GET
    /tweets/search/recent

    Search for Tweets published in the last 7 days

    Parameters
    • query*
      string - One query for matching Tweets (512 characters max)
    • max_results
      integer - The maximum number of results to return (10-100, default: 10)
    • expansions
      string - Comma-separated list of fields to expand
    • tweet.fields
      string - Comma-separated list of Tweet fields to include
    • user.fields
      string - Comma-separated list of User fields to include
    • media.fields
      string - Comma-separated list of Media fields to include
    • place.fields
      string - Comma-separated list of Place fields to include
    • poll.fields
      string - Comma-separated list of Poll fields to include
  • GET
    /users/{id}/tweets

    Returns Tweets composed by a single user, specified by the requested user ID

    Parameters
    • id*
      string - The unique identifier of the User
    • max_results
      integer - The maximum number of results to return (5-100, default: 10)
    • exclude
      string - Comma-separated list of the types of Tweets to exclude (e.g., retweets,replies)
    • expansions
      string - Comma-separated list of fields to expand
    • tweet.fields
      string - Comma-separated list of Tweet fields to include
    • user.fields
      string - Comma-separated list of User fields to include
  • POST
    /tweets

    Creates a Tweet on behalf of an authenticated user

    Parameters
    • text*
      string - The text of the Tweet (max 280 characters)
    • reply
      object - Object containing information for a reply Tweet
    • quote_tweet_id
      string - Link to the Tweet being quoted
    • poll
      object - Object containing poll options
    • media
      object - Object containing media information