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 a developer account.
Once you have an approved developer account, you will need to first create a Project. 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 an App, 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 the getting started section of our documentation.
Getting your R environment set up
First, you need to download R which you can do on the cran website.
After, to set up an environment to work with R, you can use R studio, the R extension pack for Visual Studio Code, or a Jupyter notebook if 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.