Twitter

Real-time information network.

Getting Started

Twitter is an online social microblogging service that enables users to freely send and read short messages, which are called “tweets”.

Twitter uses the @ character to mention people and the hashtag # for topics. It allows its users to reply to messages, follow them (retweet) and like them.

Creating a Twitter application

The first step to being able to use the Twitter API is to create a Twitter application from the address https://apps.twitter.com/app/new. At this point, we can specify its name and description.

Accept the “Twitter Developer Agreement”, click on the “Create” button and your application is created.

Handling security

Twitter leverages OAuth to authenticate requests and supports several scenarios. This aspect is outside the scope of the article so we don’t provide a comprehensive description of such issues. In this article, we only act as a standalone application that wants to directly use the Twitter REST API.

Let’s use the OAuth 1 support of the Twitter API. The security configuration takes place into the “Keys and Access Tokens” tab of the previously created application. We can distinguish two parts.

The first one, Application Settings, corresponds to the consumer key and consumer secret, which are related to your application. Be careful to keep the consumer secret token private. They aren’t enough to use the API in the context of your application.

The second one, Access Token, gives you tokens to authenticate your requests against the API. They allow you to link calls to a specific Twitter user. Calls will be executed on the behalf of this user. Right after having created your application, no access token is present. To generate them, simply click on the “Create my access token” button.

They are now displayed in the “Your Access Token” area.

At any time, we can regenerate tokens or even revoke them. All four tokens will be necessary to sign Twitter requests against the API.

Now we have configured all we need, let’s start to interact with the Twitter API.

Searching tweets

Since a Web API is independent of the client technology, we will first use Postman to configure and send requests.

First, create a request for the URL https://api.twitter.com/1.1/search/tweets.json. Then, start configuring security hints for OAuth 1 using the Authorization tab. You’ll  need to fill the fields with the previous tokens.

The Twitter API allows you to specify a query string here to define which tweets you want to retrieve. Here are the parameters we will use for our search:

  • Parameter q to specify the search string. For example, if you use the value “@hitchhq”, you will retrieve all the tweets mentioning the hitchhq account. Same thing “#webapi” for the hashtag webapi.
  • Parameter result_type to define if the result set will be represented by recent or popular tweets or even a mix of both.

Note that geolocalization can be used at the level of search.

After clicking on the Send button, you’ll receive the response formatted with JSON. This corresponds to a list of tweets.

Each tweet contains hints regarding:

  • The tweet itself like its text and its creation date
  • The user who creates it
  • Some entities regarding hashtags, symbols, user mentions and URLs it contains
  • Some hints about favorites and retweets, and it replies to another tweet
  • Eventually some geographical hints

The following figure describes the structure of the tweet data structure received:

Sending tweets

In the previous section, we learned how to get data from Twitter. This only consists of read operations and we now describe how to execute write operations by sending tweets. We implement a small Node application for this but the use of Postman or any HTTP client remains possible by setting security hints like previously.

To send a tweet, you can use the endpoint /statuses/update.json. Unlike responses, Twitter only supports form-encoded payload for inputs. The content of the tweet must be specified within the status entry.

Signing a request for OAuth 1 by hand is not an obvious task. In the best scenarios, HTTP client libraries sometimes provide a built-in support for this. That’s the case of the request and request-promise libraries in the context of Node.

Sending a tweet with the second one is simple as described in the following snippet:

const BASE_URL = 'https://api.twitter.com/1.1';
(...)

let oauth = {
  consumer_key: CONSUMER_KEY,
  consumer_secret: CONSUMER_SECRET,
  token: ACCESS_TOKEN,
  token_secret: ACCESS_TOKEN_SECRET
};

let options = {
  method: 'POST',
  uri: ${BASE_URL}/statuses/update.json,
  form: {
    status: 'My first tweet using the Twitter API!'
  },
  oauth
};

request(options)
  .then(function (body) {
    // Successful response
  })
  .catch(function (err) {
    // If an error occurs
});

After the request is completed, the tweet is visible on your account.

Note that it’s also possible to use links, hashtags, and images at this level. Regarding media files, we need to upload them and then reference them using the media_ids property.

Retweeting

The Twitter API also allows  retweeting a tweet programmatically. It’s very similar to send a tweet but you need to have the identifier of the source tweet. This identifier is necessary to build the endpoint URL: /statuses/retweet/<TWEET_ID>.json.

This identifier can be found using, for example, the search request of the previous section, “Searching tweets”. It corresponds to the id_str property. No input payload is required for such a request.

Retweeting a tweet programmatically can be done as described below with Node:

const BASE_URL = 'https://api.twitter.com/1.1';
(...)

let oauth = {
  consumer_key: CONSUMER_KEY,
  consumer_secret: CONSUMER_SECRET,
  token: ACCESS_TOKEN,
  token_secret: ACCESS_TOKEN_SECRET
};

// The identifier of the tweet
let tweetId = ‘782399817351823360’;
let options = {
  method: 'POST',
  uri: ${BASE_URL}/statuses/retweet/${tweetId}.json,
  oauth
};

request(options)
  .then(function (body) {
    // Successful response
  })
  .catch(function (err) {
    // If an error occurs
});

Be careful to use the id_str property and not the id one for the tweet identifier.

After the request is completed, the retweet is visible on your account.