Getting started with the GET /tweets endpoint

The endpoints we release in Labs will be previews and are likely to change before they are released broadly, so we encourage you to take that into consideration as you build. Before getting started, we encourage you to read more about Twitter Developer Labs.

The GET /tweets endpoint provides developers with information about a Tweet. The information provided by the endpoint is in the form of hydrated Tweet object. The hydrated Tweet object contains public Twitter account metadata such as name, description, location, and more, which is returned in the payload. To learn more about what data is returned in the Tweet payload, check out the Labs Tweet object data dictionary.

In the following quick start guide, we will search for the user @TwitterDev and specify a detailed response format in the request. Setting the format to detailed ensures that more detailed information about the user is returned from your request to the endpoint.

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:

  • Activating the “Tweets and Users” preview in the Labs dashboard

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

Using either one of these applications, copy your keys and tokens into the oAuth 1.0 tab before hitting send.

 

Select a method to run the API call:

  • 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 something likeAAAAAAAAAAAA0%2EUifi76ZC9Ub0wnsg3

  curl -X GET -H "Authorization: Bearer <BEARER_TOKEN>"  "https://api.twitter.com/labs/1/tweets?ids=1067094924124872705&format=detailed"

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/1/tweets?ids=1067094924124872705&format=detailed"

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": "1067094924124872705", "format": "detailed"}

# 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/1/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/1/tweets?ids=1067094924124872705&format=detailed"
@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/1/tweets');

const params = {
  ids: '1067094924124872705',
  format: 'detailed',
};

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 payload

The payload you get back from your API request will appear in JSON format, as shown below.

{
  "data": [
    {
      "id": "1067094924124872705",
      "created_at": "2018-11-26T16:37:10.000Z",
      "text": "Just getting started with Twitter APIs? Find out what you need in order to build an app. Watch this video! https://t.co/Hg8nkfoizN",
      "author_id": "2244994945",
      "attachments": {
        "media_keys": [
          "13_1064638969197977600"
        ]
      },
      "format": "compact"
    }
  ]
}

Now you've successfully used the GET /tweets endpoint.
 

Additional resources