Tweets and Users v2

Quick start contents

Please note:

We recently released new Tweet lookup and user lookup endpoints into Twitter API v2: Early Access.

Learn more about the new functionality at the following links:


Interested in exploring Labs?
The endpoints we release in Labs are previews of tools that may be released more broadly in the future, but will likely undergo changes before then. We encourage you to take that into consideration as you explore. Before getting started, please read more about Twitter Developer Labs.
 

Getting started with the GET /tweets endpoint

The GET /tweets endpoint provides developers with public Tweet data for requested available Tweets. The response includes Tweet objects in JSON format. A Tweet object contains public Tweet metadata such as id, text, created_at, lang, source, public_metrics and more. To learn more about data returned in the Tweet object, check out the "Response fields" section in the API reference or our guide on the new fields parameter.

In the following quick start guide, we will request this specific Tweet from @TwitterDev and specify a set of fields desired for the response, including one expansion for media to get additional media fields.

There are a few methods for sending requests to the users endpoint. In order to access the GET /tweets endpoint, you will need the following:

Authentication

All the endpoints in this preview are authenticated using OAuth 2.0 Bearer Token (also known as application-only authentication). This means you will need to generate a Bearer Token, and pass this token in all of your requests. Once configured, our Postman collection will handle the generation of a Bearer Token for you. Other clients like curl and Insomnia will require you to generate a token manually.

REST Client

REST applications such as Postman can be used for organizing, testing, and debugging HTTP requests.

We have compiled a collection of example requests to all Twitter Developer Labs endpoints, including the GET /tweets endpoint. Postman provides a user-interfaces for managing authentication, setting request headers, working with request parameters, and examining response JSON.

You can get started with a Labs collection by reading our "Getting started with Postman" tutorial and clicking on the following button:

 

Accessing the Tweets API

The example requests below will return a specific Tweet from @TwitterDev 

These examples illustrate the basic mechanics of the endpoint, making an authenticated request and displaying the response, but are not well suited for real-world use. One reason is that they work directly with hard-coded consumer keys and secrets, instead of loading credential tokens from another resource. Another reason is that they make a single request and stop.

These and other scripts are available in our Labs Sample Code repository.

  • cURL
  • Twurl
  • Python 3
  • Ruby
  • JavaScript (Node.js)

cURL is a command-line tool for getting or sending files using the URL syntax.

Copy the following cURL request into your command line after making changes to the following:

Replace <BEARER_TOKEN> with your own, which will look something like AAAAAAAAAAAA0%2EUifi76ZC9Ub0wnsg3

  curl -X GET -H "Authorization: Bearer <BEARER_TOKEN>"  \
"https://api.twitter.com/labs/2/tweets/1138505981460193280?expansions=attachments.media_keys&tweet.fields=created_at,author_id,lang,source,public_metrics,context_annotations,entities"

If you need to request a new Bearer Token, you can do so with the request below.  Replace the API_KEY and API_KEY_SECRET with your Consumer API Keys from the app that you used to activate the Labs preview.

  curl -X POST "https://api.twitter.com/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
-u <API_KEY>:<API_KEY_SECRET> \
--data-urlencode "grant_type=client_credentials"

Twurl is a cURL-like application, tailored specifically for the Twitter API.

 

Enter the following Twurl request into your command line:

  twurl -X GET "/labs/2/tweets/1138505981460193280?expansions=attachments.media_keys&tweet.fields=created_at,author_id,lang,source,public_metrics,context_annotations,entities"

To run this example, you will need to add your consumer key and secret to this example. To do so:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Tweets and users preview, then click Details.
  3. Select the Keys and tokens tab.
  4. In the Consumer API Keys section, copy the values for API Key into consumer_key and API Secret Key into consumer_secret.

 

Important: Never check Consumer Keys and Secrets into source control. Learn how to secure your credentials.

import os
from requests_oauthlib import OAuth1Session

consumer_key = ''  # Add your API key here
consumer_secret = ''  # Add your API secret key here

params = {"ids": "1138505981460193280", "tweet.fields": "created_at"}

# Get request token
request_token_url = "https://api.twitter.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
fetch_response = oauth.fetch_request_token(request_token_url)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
print("Got OAuth token: %s" % resource_owner_key)

# # Get authorization
base_authorization_url = 'https://api.twitter.com/oauth/authorize'
authorization_url = oauth.authorization_url(base_authorization_url)
print('Please go here and authorize: %s' % authorization_url)
verifier = input('Paste the PIN here: ')

# # Get the access token
access_token_url = 'https://api.twitter.com/oauth/access_token'
oauth = OAuth1Session(consumer_key,
                     client_secret=consumer_secret,
                     resource_owner_key=resource_owner_key,
                     resource_owner_secret=resource_owner_secret,
                     verifier=verifier)
oauth_tokens = oauth.fetch_access_token(access_token_url)

access_token = oauth_tokens['oauth_token']
access_token_secret = oauth_tokens['oauth_token_secret']

# Make the request
oauth = OAuth1Session(consumer_key,
                       client_secret=consumer_secret,
                       resource_owner_key=access_token,
                       resource_owner_secret=access_token_secret)
response = oauth.get("https://api.twitter.com/labs/2/tweets", params = params)
print("Response status: %s" % response.status_code)
print("Body: %s" % response.text)

To run this example, you will need to add your consumer key and secret to this example. To do so:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Tweets and users preview, then click Details.
  3. Select the Keys and tokens tab.
  4. In the Consumer API Keys section, copy the values for API Key into consumer_key and API Secret Key into consumer_secret.

 

Important: Never check Consumer Keys and Secrets into source control. Learn how to secure your credentials.

require 'oauth'
require 'yaml'

@consumer_key = # Add your API key here
@consumer_secret = # Add your API secret key here

@consumer = OAuth::Consumer.new(@consumer_key, @consumer_secret,
                                :site => 'https://api.twitter.com',
                                :authorize_path => '/oauth/authenticate',
                                :debug_output => false)                                

@request_token = @consumer.get_request_token()

@token = @request_token.token
@token_secret = @request_token.secret
puts "Authorize via this URL: #{@request_token.authorize_url()}"
puts "Enter PIN: "
@pin = gets.strip

@hash = { :oauth_token => @token, :oauth_token_secret => @token_secret}
@request_token  = OAuth::RequestToken.from_hash(@consumer, @hash)
@access_token = @request_token.get_access_token({:oauth_verifier => @pin})

require 'typhoeus'
require 'oauth/request_proxy/typhoeus_request'

@uri = "https://api.twitter.com/labs/2/tweets?ids=1138505981460193280&tweet.fields=created_at,author_id,lang,source,public_metrics&expansions=attachments.media_keys"
@options = {
    :method => :get
}

@oauth_params = {:consumer => @consumer, :token => @access_token}
@hydra = Typhoeus::Hydra.new
@req = Typhoeus::Request.new(@uri, @options) # :method needs to be specified in options
@oauth_helper = OAuth::Client::Helper.new(@req, @oauth_params.merge(:request_uri => @uri))
@req.options[:headers].merge!({"Authorization" => @oauth_helper.header}) # Signs the request
@hydra.queue(@req)
@hydra.run
@response = @req.response

puts @response.body

To run this example, you will need to add your consumer key and secret to this example. To do so:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Tweets and users preview, then click Details.
  3. Select the Keys and tokens tab.
  4. In the Consumer API Keys section, copy the values for API Key into consumer_key and API Secret Key into consumer_secret.

 

Important: Never check Consumer Keys and Secrets into source control. Learn how to secure your credentials.

const qs = require('querystring');
const request = require('request');
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
const util = require('util');

const get = util.promisify(request.get);
const post = util.promisify(request.post);

const consumer_key = ''; // Add your API key here
const consumer_secret = ''; // Add your API secret key here

const requestTokenURL = new URL('https://api.twitter.com/oauth/request_token');
const accessTokenURL = new URL('https://api.twitter.com/oauth/access_token');
const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
const endpointURL = new URL('https://api.twitter.com/labs/2/tweets');

const params = {
  ids: '1138505981460193280',
  'tweet.fields': 'created_at',
};

async function input(prompt) {
  return new Promise(async (resolve, reject) => {
    readline.question(prompt, (out) => {
      readline.close();
      resolve(out);
    });
  });
}

async function requestToken() {
  const oAuthConfig = {
    callback: 'oob',
    consumer_key: consumer_key,
    consumer_secret: consumer_secret,
  };

  const req = await post({url: requestTokenURL, oauth: oAuthConfig});
  if (req.body) {
    return qs.parse(req.body);
  } else {
    throw new Error('Cannot get an OAuth request token');
  }
}

async function accessToken({oauth_token, oauth_token_secret}, verifier) {
  const oAuthConfig = {
    consumer_key: consumer_key,
    consumer_secret: consumer_secret,
    token: oauth_token,
    token_secret: oauth_token_secret,
    verifier: verifier,
  }; 
  
  const req = await post({url: accessTokenURL, oauth: oAuthConfig});
  if (req.body) {
    return qs.parse(req.body);
  } else {
    throw new Error('Cannot get an OAuth request token');
  }
}



async function getRequest({oauth_token, oauth_token_secret}) {
  const oAuthConfig = {
    consumer_key: consumer_key,
    consumer_secret: consumer_secret,
    token: oauth_token,
    token_secret: oauth_token_secret,
  };

  const req = await get({url: endpointURL, oauth: oAuthConfig, qs: params, json: true});
  if (req.body) {
    return req.body;
  } else {
    throw new Error('Cannot get an OAuth request token');
  }
}

(async () => {
  try {

    // Get request token
    const oAuthRequestToken = await requestToken();
    
    // Get authorization
    authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
    console.log('Please go here and authorize:', authorizeURL.href);
    const pin = await input('Paste the PIN here: ');
    
    // Get the access token
    const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());

    // Make the request
    const response = await getRequest(oAuthAccessToken);
    console.log(response);
  } catch(e) {
    console.error(e);
    process.exit(-1);
  }
  process.exit();
})();

Tweet response

The response for the Tweets request shown above will look like the JSON payload below.

{
    "data": {
        "attachments": {
            "media_keys": [
                "7_1138489597158199298"
            ]
        },
        "author_id": "2244994945",
        "context_annotations": [
            {
                "domain": {
                    "id": "45",
                    "name": "Brand Vertical",
                    "description": "Top level entities that describe a Brands industry"
                },
                "entity": {
                    "id": "781974596165640193",
                    "name": "Technology"
                }
            },
            {
                "domain": {
                    "id": "46",
                    "name": "Brand Category",
                    "description": "Categories within Brand Verticals that narrow down the scope of Brands"
                },
                "entity": {
                    "id": "781974596752842752",
                    "name": "Services"
                }
            },
            {
                "domain": {
                    "id": "47",
                    "name": "Brand",
                    "description": "Brands and Companies"
                },
                "entity": {
                    "id": "10045225402",
                    "name": "Twitter"
                }
            }
        ],
        "created_at": "2019-06-11T17:59:13.000Z",
        "entities": {
            "annotations": [
                {
                    "start": 44,
                    "end": 65,
                    "probability": 0.3687,
                    "type": "Product",
                    "normalized_text": "Twitter Developer Labs"
                }
            ],
            "urls": [
                {
                    "start": 174,
                    "end": 197,
                    "url": "https://t.co/eNx4Wc3Qwj",
                    "expanded_url": "https://twittercommunity.com/t/twitter-developer-labs-is-open-to-all-developers/126717",
                    "display_url": "twittercommunity.com/t/twitter-deve…",
                    "images": [
                        {
                            "url": "https://pbs.twimg.com/news_img/1198608207737806848/EPekNT6H?format=jpg&name=orig",
                            "width": 1200,
                            "height": 630
                        },
                        {
                            "url": "https://pbs.twimg.com/news_img/1198608207737806848/EPekNT6H?format=jpg&name=150x150",
                            "width": 150,
                            "height": 150
                        }
                    ],
                    "status": 200,
                    "title": "Twitter Developer Labs is open to all developers",
                    "description": "Following our initial announcement, we’re excited to share that Twitter Developer Labs is now available to all developers! Twitter Developer Labs is a new program to let developers test new API endpoints and share feedback as we build the new generation of the Twitter API. Since the endpoints we will release in Labs are early previews, they may change before we release them broadly. We encourage you to take that into consideration as you build with them. For example, this might mean they’re not...",
                    "unwound_url": "https://twittercommunity.com/t/twitter-developer-labs-is-open-to-all-developers/126717"
                },
                {
                    "start": 198,
                    "end": 221,
                    "url": "https://t.co/ucmZrJAYjk",
                    "expanded_url": "https://twitter.com/TwitterDev/status/1138505981460193280/video/1",
                    "display_url": "pic.twitter.com/ucmZrJAYjk"
                }
            ]
        },
        "id": "1138505981460193280",
        "lang": "en",
        "public_metrics": {
            "retweet_count": 107,
            "reply_count": 31,
            "like_count": 258,
            "quote_count": 36
        },
        "source": "Twitter Web Client",
        "text": "🎺 da-dada-DAH! We’re introducing the first Twitter Developer Labs endpoints: \n\n✨GET/users and GET/tweets ✨\n\nLabs is now open to all developers to start experimenting today 👉 https://t.co/eNx4Wc3Qwj https://t.co/ucmZrJAYjk"
    },
    "includes": {
        "media": [
            {
                "media_key": "7_1138489597158199298",
                "type": "video"
            }
        ]
    }
}

 


 

Additional resources

Was this document helpful?

Thank you

Thank you for the feedback. We’re really glad we could help!

Thank you for the feedback. How could we improve this document?

Thank you for the feedback. Your comments will help us improve our documents in the future.