Tweets and Users v2

Quick start contents

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.

Still using v1?
This page documents the current version of these endpoints, however you can still reference the previous version. You should also check out our version migration guide and review our changelog.
 

Getting started with the GET /users endpoint

The GET /users endpoint provides developers with public user data for requested available users. The information returned by the endpoint includes user objects in JSON format. A user object contains public Twitter account metadata such as id, name, username, created_at, description, pinned_tweet_id and more. To learn more about data returned in the User 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 the user @TwitterDev and specify a set of fields desired for the response.

There are a few steps required before sending requests. In order to access the GET /users 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 /users 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 Users API

The example requests below will return the user object for the user @TwitterDev.

The following code examples should help you starting making search requests from code. Below you will find examples in Python, Ruby, and Node.js.

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)
  • Java

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

Select your app from the dropdown. Make sure the app is enabled for Tweets and Users.

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/users/by?usernames=twitterdev&user.fields=created_at,description,pinned_tweet_id"

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/users/by?usernames=twitterdev&user.fields=created_at,description,pinned_tweet_id"

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
​
# Add your API key here
consumer_key = ""
# Add your API secret key here
consumer_secret = ""
​
fields = "created_at,description,pinned_tweet_id"
params = {"usernames": "TwitterDev", "user.fields": fields}
​
# 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/users/by?", params=params)
print(response)
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'

puts "Looking up users with new access token"

@uri = "https://api.twitter.com/labs/2/users/by?usernames=TwitterDev"
@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/users/by');

const params = {
  usernames: 'TwitterDev',
};

async function input(prompt) {
  return new Promise(async (resolve, reject) => {
    readline.question(prompt, (out) => {
      readline.close();
      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}) {
  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();
})();

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.

/*
 * Sample code to demonstrate the use of the v2 Tweets endpoint
 * */
public class UsersDemo {

  //FIXME Replace the keys below with your own keys and secret
  private static final String CONSUMER_KEY = "";
  private static final String CONSUMER_SECRET = "";

  public static void main(String args[]) throws IOException, URISyntaxException {
    //Replace comma separated usernames with usernames of your choice
    String response = getUsers("TwitterDev,TwitterEng");
    System.out.println(response);
  }

  /*
   * This method calls the v2 Users endpoint with usernames as query parameter
   * */
  private static String getUsers(String usernames) throws IOException, URISyntaxException {
    String userResponse = null;

    HttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(RequestConfig.custom()
            .setCookieSpec(CookieSpecs.STANDARD).build())
        .build();

    URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/labs/2/users/by");
    ArrayList<NameValuePair> queryParameters;
    queryParameters = new ArrayList<>();
    queryParameters.add(new BasicNameValuePair("usernames", usernames));
    queryParameters.add(new BasicNameValuePair("user.fields", "created_at,description,pinned_tweet_id"));
    uriBuilder.addParameters(queryParameters);

    HttpGet httpGet = new HttpGet(uriBuilder.build());
    httpGet.setHeader("Authorization", String.format("Bearer %s", getAccessToken()));
    httpGet.setHeader("Content-Type", "application/json");

    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    if (null != entity) {
      userResponse = EntityUtils.toString(entity, "UTF-8");
    }
    return userResponse;
  }

  /*
   * Helper method that generates bearer token by calling the /oauth2/token endpoint
   * */
  private static String getAccessToken() throws IOException, URISyntaxException {
    String accessToken = null;

    HttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(RequestConfig.custom()
            .setCookieSpec(CookieSpecs.STANDARD).build())
        .build();

    URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/oauth2/token");
    ArrayList<NameValuePair> postParameters;
    postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
    uriBuilder.addParameters(postParameters);

    HttpPost httpPost = new HttpPost(uriBuilder.build());
    httpPost.setHeader("Authorization", String.format("Basic %s", getBase64EncodedString()));
    httpPost.setHeader("Content-Type", "application/json");

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    if (null != entity) {
      try (InputStream inputStream = entity.getContent()) {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);
        accessToken = jsonMap.get("access_token").toString();
      }
    }
    return accessToken;
  }

  /*
   * Helper method that generates the Base64 encoded string to be used to obtain bearer token
   *
   * */
  private static String getBase64EncodedString() {
    String s = String.format("%s:%s", API_KEY, API_SECRET);
    return Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
  }
}

Users response

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

{
  "data": [
    {
      "created_at": "2013-12-14T04:35:55.000Z",
      "description": "The voice of Twitter's #DevRel team, and your official source for updates, news, & events about Twitter's API.\n\nNeed help? Visit https://t.co/DVDf7qKyS9",
      "id": "2244994945",
      "name": "Twitter Dev",
      "pinned_tweet_id": "1214281000932593667",
      "username": "TwitterDev"
    }
  ]
}

 


 

Additional resources