Getting started with R and v2 of the Twitter API (2024)


This tutorial will walk through what you need to get started with the programming language R and the Twitter API v2. Using R to connect to the user lookup endpoint, I’ll show how to work with JSON returned from the Twitter API. User lookup is a GET method and returns information about a user or group of users, specified by a user ID or a username.

If you aren’t familiar, R is one of the most popular languages for common Data Science tasks like time-series analysis, modeling, visualization, and other data analysis, and is often used in conjunction with the Twitter API. With the user lookup endpoint, you can use the user object to determine a correlation between the number of followers a person has and the sentiment score of their bio. The user object may also be used to map a group of accounts based on the location publicly listed in their profiles.

Getting started with the Twitter API

Before you can use the Twitter API v2, you will need to sign up for adeveloper account.

Once you have an approved developer account, you will need to first create aProject. Projects allow you to organize your work based on how you intend to use the Twitter API, so you can effectively manage your access to the API, and monitor your usage.

Each Project contains anApp, with which you can generate the credentials required to use the Twitter API. You can learn more about how to get started with the Twitter API, in thegetting startedsection of our documentation.

Getting your R environment set up

First, you need todownload Rwhich you can do on thecran website.

After, to set up an environment to work with R, you can useR studio, the R extension pack forVisual Studio Code, or aJupyter notebookif you come from the Python world.

Setting up your environment variable

For the code examples, I’m going to be showing today, you will want to create an environment variable for your bearer token. The Bearer Token is what allows you to authenticate to the Twitter API and start making requests. First, replace “your-bearer-token” with your own bearer token, which can be obtained from the keys and tokens section of your App in the developer portal. You’ll need to run this line of code in the console before you start writing a script.

Making your request

You can use the packagehttrto make HTTP requests to the Twitter API. If you haven’t already installed this, please install the package in your console. You will also need to installjsonliteto work with our JSON object anddplyrfor data manipulation.

You can now begin writing your R script to connect to the API. At the top of the file, call the packageshttr,jsonlite, anddplyr.

The first step in your code sample is to get set up to authenticate to the Twitter API. Grab the Bearer Token you pulled from your App, and pass that into your headers for authentication. In the below example, replace $BEARER_TOKEN with your token.

Once you got your authentication set up, define the parameters of your request. By default, you will get back the id, name, and username of each user you get back. You can make adjustments to this payload by adding additionalfieldsandexpansions. For this example, you will want the profile bio of the user which is requested using user.fields=description, and an expansion that contains the pinned Tweet of the user.

Now you are ready to format your URL with the Twitter handle, also known as account, you are looking to get more information about. Use thereadlinemethod to allow this sample to be reusable. After you type the handle you want to look at, format your URL to contain the handle you define by replacing $USERNAME with the desired Twitter handle.

At this point, use thehttrpackage to make a GET request to the URL you just created, pass in our authentication credential via the header, and pass in the parameters you defined. You can save the response as a text object in the variable obj and print this out to view the result of the request you made.

Working with our JSON payload

One of my favorite ways to work with a JSON is to use a data frame, which allows you to easily access complex nested data. To do this, use thefromJSONmethod of thejsonlitepackage to flatten your file to allow the fields to be in the same object. Then, pass that object into a data frame. Now you are ready to view this data frame.

You can access the fields of the data from the data frame and pass them into a string that has the handle, the username, and bio.

Usecatinstead of print to view the object with newlines between each field you are pulling.

If you had multiple handles you made requests for, you could easily use a loop to access each data frame element.


Hopefully, this tutorial can be a starting place to work with R and the Twitter API. As a next step, you may want to look at our R samples for recent search, Tweet lookup and user lookup in ourv2 sample code. Be sure to let us know on theforumsif you run into any troubles along the way or Tweet us at@TwitterDevif this tutorial inspires you to create anything.

Getting started with R and v2 of the Twitter API (2024)


How to get 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.

How to use Twitter API with R? ›

You can use the package httr to make HTTP requests to the Twitter API. If you haven't already installed this, please install the package in your console. You will also need to install jsonlite to work with our JSON object and dplyr for data manipulation. You can now begin writing your R script to connect to the API.

How much is Twitter v2 API? ›


What is the difference between Twitter API v1 1 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.

Is Twitter API no longer available? ›

As announced previously, we have deprecated our legacy Twitter API access tiers. Thus, essential and elevated packages are no longer available. Applications and projects have been placed in the appropriate new Free access tier.

What is Twitter v2? ›

What's new with v2? We're building a new Twitter API with a modern and more sustainable foundation as well as an improved developer experience. The first endpoints are now available within Early Access, and enable you to listen to and analyze the public conversation.

How to extract Twitter data using R? ›

Step 1: Login with your Twitter login details. Step 4: Check the option 'Yes, I agree' under Developer Agreement and Click on 'your Twitter application'. Step 8:Replace consumer Key with your Consumer key and consumer Secret and run the code from lines 10 to 14 & also run lines 16 & 17.

Is using Twitter API free? ›

After weeks of stalling, Twitter finally announced its new API price structures on Wednesday. These three tiers include a bare-bone free level mostly meant for content posting bots, a $100 per month basic level and a costly enterprise level.

How do I get Twitter API approved? ›

If you don't have one, create Twitter API key.
  1. Step 1: Launch a Twitter developer account. ...
  2. Step 2: Apply for a developer's account. ...
  3. Step 3: Choose the reason for using Twitter API key. ...
  4. Step 4: Fill in the required fields. ...
  5. Step 5: Answer detailed questions about your future app. ...
  6. Step 6: Check the information.
Jan 19, 2024

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 the difference between free and basic Twitter API? ›

Free — Write-only access with the ability to post 1,500 tweets per month at no cost. Basic — A $100 per month subscription for hobbyists with the option of posting 3,000 tweets per month at the user level, or 50,000 tweets per month at the app level. The read limit is 10,000 tweets.

What is API v2? ›

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.

Is Twitter API paid now? ›

Twitter has recently stopped offering free access to its API, provoking a turmoil in the advertising industry. Due to the pricing options offered by Twitter, many companies are now seeking alternatives to the Twitter API by turning to data provider companies that have access to vast amounts of data streams.

What is the alternative to Twitter API? ›

Best Paid & Free Alternatives to Twitter API
  • Meltwater.
  • Hootsuite.
  • Sprinklr Social.
  • Sprout Social.
  • CisionOne.
  • Brand24.
  • Brandwatch Social Media Management.
  • Semrush.

Is Twitter API RESTful? ›

Validate the API success in the Twitter profile

Here you can see the tweet is been successfully posted in your Twitter account with help of the RESTful API which we have implemented above.

How do I add Twitter API v2 to postman? ›

To add your keys and tokens to the “Twitter API v2” environment, click on the “manage environments” button in the top right corner of Postman., you will need to click on the settings button in the top right corner. From the list of environments, click on “Twitter API v2”.

When was Twitter API v2 released? ›

X Developer Platform originally launched Early Access to give developers a preview of the v2 API back in June 2020, and in November 2021 we launched a production ready, stable version of v2 for all developers. The functionality available within X API v2 serves the majority of developers on the platform.

How do I get Twitter API data? ›

How to get access to the X API
  1. Step one: Sign up for a developer account. Signing up for a developer account is quick and easy! ...
  2. Step two: Save your App's key and tokens and keep them secure. ...
  3. Step three: Make your first request.


Top Articles
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5231

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.