Getting started with the metrics 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 metrics endpoint provides developers with access to engagement metrics for owned/authorized Tweets. This includes access to private metric types, such as impressions, and video view quartiles, as well as access to public metric types, such as Retweets, Quote Tweets, likes, replies, and video views.

Before you can start, you will need the following:

Authentication

The metrics endpoint requires the use of HTTPS. All requests must use OAuth 1.0a (also known as user-context authorization). This means that you must use the API key and secret of your Twitter developer app, as well as the Tweet owner's access token and access token secret to make a request to the endpoint. If you need to generate an access token and secret for the Tweet owner, you can do so with the 3-legged OAuth process.

If you plan to use a developer tool such as Twurl or a REST client app, it is important for you to keep the following in mind:

 

REST client

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

Accessing GET /tweets/metrics/private

Running the below request will return hydrated JSON objects for the Tweet ID(s) you want to query

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:

  • You will need to replace the values for oauth_consumer_key, oauth_nonce, oauth_signature, oauth_timestamp and oauth_token with your own. You can obtain these by using a REST client such as Postman or Insomia.  
  • You will also need to enter one or several comma-seperated Tweet ID(s) from owned/authorized account(s) where it says tweet_id
    curl --request GET \
  --url 'https://api.twitter.com/labs/1/tweets/metrics/private?ids=tweet_id' \
  --header 'authorization: OAuth oauth_consumer_key="oauth_consumer_key", oauth_nonce="oauth_nonce", oauth_signature="oauth_signature", oauth_signature_method="HMAC-SHA1", oauth_timestamp="oauth_timestamp", oauth_token="oauth_token", oauth_version="1.0"'
  

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

Enter the following Twurl request into your command line:

  • You will need to enter one or several comma-separated Tweet ID(s) from an owned account where it says `tweet_id`.
    twurl -X GET "/labs/1/tweets/metrics/private?ids=tweet_id"
  

To run this example, you will need to add your consumer key and secret to this example. You will also have to enter one or several comma-seperated Tweet ID(s) from owned/authorized account(s) as indicated towards the bottom of this example. 

 

To add your consumer key and secret:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Metrics 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.

    from requests_oauthlib import OAuth1Session
import json
import pprint

# Authentication
# Add your API key here
consumer_key = ""
# Add your API secret key here
consumer_secret = ""

request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob"
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: {}".format(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: {}".format(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,
)

# Add the Tweet ID for the Tweet you are looking for. You can add up to 50 comma seperated IDs.
params = {"ids": ""}

response = oauth.get(
    "https://api.twitter.com/labs/1/tweets/metrics/private", params=params
)

# Pretty print the response
pprint.pprint(json.loads(response.text))
  

To run this example, you will need to add your consumer key and secret to this example. You will also have to enter one or several comma-seperated Tweet ID(s) from owned/authorized account(s) as indicated towards the bottom of this example. 

 

To add your consumer key and secret:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Metrics 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'
require 'json'
require 'typhoeus'
require 'oauth/request_proxy/typhoeus_request'

# Authentication

# Add your API key here
@consumer_key = ''

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

@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})

puts "Looking up Tweet metrics with new access token"

# Parameters: Add up to 50 comma-separated Tweet ID(s) you wish to query here
@TweetIDs = ''

@uri = "https://api.twitter.com/labs/1/tweets/metrics/private?ids=%s" % [@TweetIDs]  
@options = {
    :method => :get
}
@oauth_params = {
    :consumer => @consumer,
    :token => @access_token
}
@hydra = Typhoeus::Hydra.new
@req = Typhoeus::Request.new(@uri, @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. You will also have to enter one or several comma-seperated Tweet ID(s) from owned/authorized account(s) as indicated towards the bottom of this example. 

 

To add your consumer key and secret:

  1. Navigate to your app dashboard.
  2. Select the app you've enabled with the Metrics 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
const consumer_secret = ''; // Add your API secret key

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/metrics/private');

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

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 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 getRequest({
  oauth_token,
  oauth_token_secret
}, params) {
  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());

    // You can input up to 50 comma-separated Tweet IDs.
    const params = {
      ids: ''
    };

    // Make the request and return response
    const response = await getRequest(oAuthAccessToken, params);
    console.log(response.data)
    if (response.hasOwnProperty('errors')) {
      console.log(response.errors)
    }

  } catch (e) {
    console.error(e);
    process.exit(-1);
  }
  process.exit();
})();
  

Response payload

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

    {
  "data": [
    {
      "tweet_id": "123456789",
      "tweet": {
        "like_count": 1,
        "retweet_count": 2,
        "quote_count": 3,
        "reply_count": 4,
        "impression_count": 5
      },
      "video": {
        "media_key": "13_123456789",
        "view_count": 12345,
        "playback_0_count": 50,
        "playback_25_count": 40,
        "playback_50_count": 30,
        "playback_75_count": 20,
        "playback_100_count": 10
      }
    }
  ],
  "errors": [
    {
      "value": "1",
      "detail": "Could not find tweet with ids: [1].",
      "type": "https://api.twitter.com/labs/1/problems/resource-not-found",
      "title": "Not Found Error",
      "parameter": "ids",
      "resource_type": "tweet"
    }
  ]
}
  

 

Additional resources