Getting started with the GET /users 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 /users endpoint provides developers with information about a Twitter user. The information provided by the endpoint is in the form of hydrated user objects. The hydrated user object contains public Twitter account metadata such as name, description, location, and more, which is returned in the payload. A payload is the data that is returned from a request to the API. To learn more about what data is returned in the user payload, check out the Labs user 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 /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.

 

Accessing the Users API

Running the below request will return hydrated user objects for the user @TwitterDev in a detailed format.

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.

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

Copy the following code request into your command line.

  # Get your bearer token
BEARER_TOKEN=$(curl -u '$CONSUMER_API_KEY:$CONSUMER_API_SECRET' 'https://api.twitter.com/oauth2/token' --data 'grant_type=client_credentials' | grep -o 'access_token":".*[^"}]' | cut -b16-)

# Makes the API request
curl -X GET -H "Authorization: Bearer $BEARER_TOKEN"  "https://api.twitter.com/labs/1/users?usernames=TwitterDev&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/users?ids=&usernames=TwitterDev&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 = {"usernames": "TwitterDev"}

# 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/users", 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'

puts "Looking up users with new access token"

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

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();
})();

Users response payload

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

{
  "data": [
    {
      "id": "2244994945",
      "created_at": "2013-12-14T04:35:55.000Z",
      "name": "Twitter Dev",
      "username": "TwitterDev",
      "protected": false,
      "location": "Internet",
      "url": "https://t.co/FGl7VOULyL",
      "description": "Your official source for Twitter Platform news, updates & events. Need technical help? Visit https://t.co/mGHnxZU8c1 ⌨️ #TapIntoTwitter",
      "verified": true,
      "entities": {
        "url": {
          "urls": [
            {
              "start": 0,
              "end": 23,
              "url": "https://t.co/FGl7VOULyL",
              "expanded_url": "https://developer.twitter.com/",
              "display_url": "developer.twitter.com"
            }
          ]
        },
        "description": {
          "urls": [
            {
              "start": 93,
              "end": 116,
              "url": "https://t.co/mGHnxZU8c1",
              "expanded_url": "https://twittercommunity.com/",
              "display_url": "twittercommunity.com"
            }
          ],
          "hashtags": [
            {
              "start": 120,
              "end": 135,
              "tag": "TapIntoTwitter"
            }
          ]
        }
      },
      "profile_image_url": "https://pbs.twimg.com/profile_images/880136122604507136/xHrnqf1T_normal.jpg",
      "stats": {
        "followers_count": 502140,
        "following_count": 1472,
        "tweet_count": 3393,
        "listed_count": 1519
      },
      "format": "detailed"
    }
  ]
}



Additional resources