Stream Tweets in real-time with v2 of the Twitter API (2024)

Tony Vu for XDevelopers

Posted on • Updated on

Stream Tweets in real-time with v2 of the Twitter API (3) Stream Tweets in real-time with v2 of the Twitter API (4) Stream Tweets in real-time with v2 of the Twitter API (5) Stream Tweets in real-time with v2 of the Twitter API (6) Stream Tweets in real-time with v2 of the Twitter API (7)

#twitter #tutorial #beginners

Introduction

The Twitter API allows you to stream public Tweets from the platform in real-time so that you can display them and basic metrics about them.

In this tutorial, you will learn how to:

Prerequisites

Steps to consider

Step 1: Set an objective for your work

First, define what you want to accomplish and decide on the data you need to meet that objective.

  • Staying informed on a topic of interest: For example, you would like to stay current on updates, news, and events about Twitter’s API.
  • Detecting current trends: You have a hard time detecting current trends and would like to extract signals about what people are discussing in the world.

Step 2: Plan and prepare to process the needed data

Staying informed on a topic of interest

For the example of staying informed on a topic of interest, you will need to decide on what type of data you need and how to go about getting it in real time.

For example, in continuing with the example on keeping current with updates to the Twitter API, you will need to make sure you get Tweets from the @TwitterDev and the @TwitterAPI accounts the moment they are posted. You will also only want Tweets that contain links so that you can read up on any further context provided with a Tweet.

To get this kind of data in real time, you can use the filtered stream endpoints. The filtered stream endpoints requires you to define filtering criteria in order for it to know what kind of Tweets to send to you.

After defining your filtering criteria, you will need to apply this to the filtered stream endpoints.

Filtering criteria are applied to the filtered stream endpoints in the form of rules. Rules allow you to narrow down to only the Tweets you are looking for by using a set of operators.

While creating a filter it is often helpful to think about what type of data you don’t want to receive and work backward from there. You will need to make sure you have the right keyword and adjust your rule to prevent unwanted Tweets from entering into your stream. For examples of how you can build more complex rules, see our documentation on building a rule.

Based on the filtering criteria just defined, you can create a rule containing the following operators.

  • from:

  • has:links

The “from:” operator matches any Tweet from a specific user and the “has:links” operator matches Tweets containing links in the Tweet body. Together, these operators form the following rule which instructs the filtered stream endpoints to filter for Tweets from the accounts @Twitterdev or @TwitterApi that contain links.

(from:twitterdev OR from:twitterapi) has:links

To add this rule, issue a POST request to the filtered stream rules endpoint with an added payload as an array of rules and operators. The example below shows how you can use cURL to do so. To authenticate, replace $BEARER_TOKEN (including the dollar sign) with the Bearer Token from your App in the developer portal

curl -X POST 'https://api.twitter.com/2/tweets/search/stream/rules' \ -H "Content-type: application/json" \ -H "Authorization: Bearer $BEARER_TOKEN" -d \ '{ "add": [ {"value": "(from:twitterdev OR from:twitterapi) has:links"} ] }'`

You can also POST to the rules endpoint using one of our code samples

Detecting current trends

For the example of detecting current trends, you will need to consider what kind of data you need and how much data you need in order to perform your analysis. For example, you may need to read and analyze a broad, but relatively manageable set of Tweets. This data should also be current or relatively current. While the text of a Tweet will likely be important for your analysis, there are other data elements you will need to consider. Within the text of a Tweet itself, you will also need to consider if you need hashtags, mentions, or if you are looking for certain keywords.

Beyond the text of a Tweet, a Tweet contains several different fields of data so you will want to decide which fields would best aid your trend detection needs. Based on the fields you decide on, you can then, for example, perform some basic frequency analysis on keywords, hashtags, mentions, or Tweet annotations made available in a Tweet payload. By default, you will only get back the id and text of each Tweet. If you would like additional data returned about each Tweet, you can add additional fields and expansions to your request URL.

After formulating your data requirements, you will need to figure out how to go about getting this data. To get the data for this analysis, the 1% random sample of public Tweets provided by the sampled stream endpoint can meet this need since it provides a small subset of data relative to the total amount of public Tweets. Additionally, the data is sent to you in real time as it happens, which will meet the requirement of the data being current.

Step 3: Connect and authenticate to the appropriate endpoint

Staying informed on a topic of interest

Once you have defined your data and set your filtering criteria using rules, you can connect to the filtered stream streaming endpoint to start getting data. The example below shows how you can use cURL to do so. To authenticate, replace $BEARER_TOKEN with the Bearer Token from your App in the developer portal.

curl -X GET -H "Authorization: Bearer $BEARER_TOKEN" "https://api.twitter.com/2/tweets/search/stream"

You can also POST to the streaming endpoint using one of our code samples

Detecting current trends

To connect to the sampled stream endpoint, issue a GET request to the endpoint. The example below shows how you can use cURL to do so. To authenticate, replace $BEARER_TOKEN with the Bearer Token from your App in the developer portal.

curl -X GET -H "Authorization: Bearer $BEARER_TOKEN" "https://api.twitter.com/2/tweets/sample/stream"

You can also connect to the sampled stream endpoint using one of our code samples

Step 4: Handle errors and disconnections

At any time while you are connected to either the filtered stream endpoint or the sampled stream endpoint, you may be disconnected either voluntarily or involuntarily. Voluntary disconnects occur when you independently terminate the connection to the streaming endpoint, whether because your code actively closes the connection, or where network settings terminate the connection. Involuntary disconnections occur when either streaming endpoint actively disconnects your App from the stream. These types of disconnections occur due to one of the following reasons.

  • Full Buffer: Your App is not reading the data fast enough, or a network bottleneck is slowing data flow.

  • Too many connections: Your App established too many simultaneous connections to the data stream. When this occurs, the filtered stream endpoint will wait 1 minute, and then disconnect the most recently established connection if the limit is still being exceeded.

  • Server maintenance: The Twitter team deployed a change or update to the system servers

You should build the proper logic into your code to automatically reconnect in the event any of these involuntary disconnections occur. Additionally, if you only need Tweets for a limited time, you may want to consider building in the proper timing in you code to disconnect from the streaming endpoint after your desired period of time has passed.

To avoid full buffer errors due to the high volume of Tweets that you will receive, your code should not do any real processing work as it reads the stream. Read the stream and then hand the activity to another thread or process to do your processing asynchronously. This processing can include performing frequency analysis or any type of heavy processing work.

For an example of how to build in reconnection logic to your application, check out the sample apps below that use the filtered stream endpoints.

Step 5: Display Tweets and basic metrics about them

Once you are reliably getting your data, you will then need to think about what you would like to do with them. One common option is to display some of them on a web page or dashboard, along with some basic metrics to describe what’s happening over time.

You should keep in mind that id and text will always be populated since they are the basic building blocks of a Tweet, but other fields may not always be present. For instance, not all Tweets will contain image attachments. You will want to consider what fields the data you are looking for is located in, which you would like to display, and which may not always be present, dependent upon the nature of the Tweet. Lastly, you will also want to reference and comply with Twitter’s Display Requirements when displaying Tweets. Using embedded Tweets can help meet these requirements.

If you would like to keep a running total of the number of Tweets read over time and display this in a chart, you should keep in mind that the amount of Tweets can fluctuate based on how much more or less people are Tweeting at a given time. You may want to create a visualization to display these fluctuations over time. Additionally, as you are ingesting and displaying these Tweets, you may want to temporarily save them to a data store and display the most recent ones or organize them on a page by page basis due to the amount of Tweets that can come in at once and your limited screen real estate. You can also consider displaying Tweets based on their organic performance metrics such as the ones receiving the most retweets, replies, or likes.

Finally, consider that Tweets can be related to one another either because someone retweets a Tweet or replies to a Tweet. If helpful towards your objective, you may want to display Tweets in a way to indicate this relationship, if any.

Next steps

Stream Tweets in real-time with v2 of the Twitter API (2024)

FAQs

What is the difference between Twitter API v1 and v2? ›

The standard v1. 1 /lists/statuses endpoint allows you to return up to 5000 Posts per request. The new v2 endpoints allow you to return up to 100 Posts per request.

How many Tweets can a developer access each month through Twitter API v2 for free? ›

As per the information provided on the Twitter Developer website, the Free Tier provides rate-limited access to v2 tweet posting and media upload endpoints, with a limit of 1,500 Tweets per month for posting at the app level.

What is Twitter API v2? ›

twitter-api-v2 is meant to provide full endpoint wrapping, from method name to response data, using descriptive typings for read/write/DMs rights, request parameters and response payload. A small feature comparison with other libs: Package. API version(s) Response typings.

How to get real-time data from Twitter? ›

To get this kind of data in real time, you can use the filtered stream endpoints. The filtered stream endpoints requires you to define filtering criteria in order for it to know what kind of Tweets to send to you. After defining your filtering criteria, you will need to apply this to the filtered stream endpoints.

What is the difference between v1 and v2 API? ›

The V1 network API allows users to override the distributionGroupId attribute at line level that allows fetching availability of multiple distribution groups in a single call. The V2 network API doesn't allow this.

Is Twitter API no longer available? ›

On September 20, 2023, X (formerly known as Twitter) will no longer support several v1. 1 API endpoints. As a result of this deprecation, several Sprout Social features will be changing.

What are the free limitations of Twitter API? ›

The free tier provides only 1,500 post requests per month along with access to Login with Twitter. The basic tier — which is deemed “for hobbyists or students” — provides 50,000 post requests and 10,000 read requests per app per month.

What is the daily limit for Twitter API? ›

Standard API v1.

You can only post 300 Tweets or Retweets during a 3 hour period. For example, if your Twitter app makes 200 requests to the POST statuses/update endpoint within a three hour period, your app will only be able to make 100 requests to the POST statuses/retweet/:id endpoint during that period.

Can I still use Twitter API for free? ›

Twitter will start charging for access to their free API from February 9, meaning third-party software developers who access API data to promote their own projects, like bots on the app, will only have access through a “paid basic tier”—though CEO Elon Musk says he'll make concessions for bots with “good content.”

How to get access to Twitter API v2? ›

  1. Step 1: Sign up for access. In order to get started with the new Twitter API, you need a developer account. ...
  2. Step 2: Create a Project and connect an App. Next, in the developer portal, create a new Project. ...
  3. Step 3: Make an HTTP request to one of the new endpoints.

What is a v2 API? ›

The v2 API is a modernized self-documenting API interface covering most current Solr APIs. It is anticipated that once the v2 API reaches full coverage, and Solr-internal API usages like SolrJ and the Admin UI have been converted from the old API to the v2 API, the old API will eventually be retired.

What are the new rules for Twitter API? ›

Twitter announced in April that access to the API will now require a paid subscription, with those most useful to researchers ranging from $42,000 to $210,000 per month. The change has left many policy shops, NGOs, independent researchers and students without access.

Is Twitter Stream API free? ›

Starting February 9, 2023, Twitter no longer supports free access to the Twitter API. The developers and companies have three options to choose from: Standard – to be used by write-only use cases and testing purposes of the Twitter API – Free with the limit of 1,500 posts per month.

How to consume streaming API? ›

Overview
  1. Step 1: Configure your stream. If you are using either the Decahose or Firehose, you don't need to configure your stream. ...
  2. Step 2: Connect to the API. ...
  3. Step 3: Consume the data as it's delivered. ...
  4. Step 4: When disconnected, reconnect to the API.

How do I see tweets by time? ›

Dates: To do an X search for certain time periods, use Twitter's date settings. By setting “since:YYYY-MM-DD ” and “*ntil:YYYY-MM-DD” dates, searching tweets by date is possible for a single day or for a multi-month or -year period. For example, you can see what users said during a campaign, event, or viral moment.

Can I still use Twitter API v1? ›

v1. 1 is no longer available. You should migrate to Twitter API v2.

What is the difference between DX API v1 and v2? ›

This approach allows for the use of standard assets, such as sections and harnesses, and as a result, makes v1 the optimal choice for existing applications. DX API Version 2 improves upon v1 by providing a significantly different approach that optimizes the number of messages (chattiness) and their structure.

What is v2 APIs? ›

The v2 API is a modernized self-documenting API interface covering most current Solr APIs. It is anticipated that once the v2 API reaches full coverage, and Solr-internal API usages like SolrJ and the Admin UI have been converted from the old API to the v2 API, the old API will eventually be retired.

What is the limit of Twitter API v1? ›

Standard API v1.

You can only post 300 Tweets or Retweets during a 3 hour period. For example, if your Twitter app makes 200 requests to the POST statuses/update endpoint within a three hour period, your app will only be able to make 100 requests to the POST statuses/retweet/:id endpoint during that period.

Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 5844

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.