3 min read

R Access to Twitter's V2 API

Tags: rjson httr jsonlite dplyr purrr glue

The rtweet package is still the easiest way to GET and POST Twitter data from R. However its developers are currently working on adapting it to the new API. V2 comes with a variety of new features. The one I was interested in was being able to GET the users who liked a tweet.

academictwitteR is probably the most established package that provides a quickstart entry point to the V2 API. However it requires creating an academic account in twitter, i.e. the user must be affiliated with a university. I also stumbled onto RTwitterV2 and voson.tcn which both also provide quickstarts on the V2 API, but did not explore these.

Instead I followed the tutorial Getting started with R and v2 of the Twitter API by Twitter Developer Advocate Jessica Garson that uses {httr} to interact more directly with the API. I highly recommend reading her tutorial. The code below is mostly just copied from there but changed to provide an example of getting the usernames of those that liked a tweet1.

GETting likers of tweet

Last year, twitter announced Likes lookup in API v2.

Below is a minimal example of how to find every user who liked any tweet, in my case I’ll check favoriters of my initial announcement of the pwiser package.

First you need to:

  1. Apply for a Twitter developer account.
  2. Create a project
  3. Create an app within that project2

Once you’ve done this, you’ll need to save your BEARER TOKEN somewhere secure, see Hadley’s write-up on Managing secrets and use your choice of approach. For the write-up below I’ll load the secret from the environment3.


bearer_token <- Sys.getenv("TWITTER_BEARER")
headers <- c(`Authorization` = sprintf('Bearer %s', bearer_token))

tweet_id <- "1394072770661822464"
url_handle <- glue::glue("https://api.twitter.com/2/tweets/{status_id}/liking_users", status_id = tweet_id)

response <- httr::GET(url = url_handle,
                     httr::add_headers(.headers = headers))
                     # query = params)

obj <- httr::content(response, as = "text")
x <- rjson::fromJSON(obj)

And then let’s pull out the usernames of the people who liked the tweet:

x$data %>% 
##  [1] "Rick_Scavetta"   "dikiprawisuda"   "technocrat"      "abuabara"       
##  [5] "kavenacca4"      "pheeree"         "mattansb"        "AndrewKostandy" 
##  [9] "1AliG"           "ncypris"         "jkregenstein"    "MarkDruffel"    
## [13] "pablofbaez"      "JobNmadu"        "LuisDVerde"      "dataleteo"      
## [17] "FredOnion"       "SebLammers"      "meier_flo"       "tomecicuta"     
## [21] "ameresv"         "ginanjar_utama"  "jmblanch"        "ThatBenFrost"   
## [25] "lan24hd"         "henda52"         "Md_Harris"       "EmilyRiederer"  
## [29] "pvallejomedina"  "thisisdaryn"     "ericarbailey"    "DrMeltemYucel"  
## [33] "c_welk"          "stewartli3"      "patilindrajeets" "rick_pack2"     
## [37] "AlainLesaffre"   "Carlos_Espeleta" "ellamkaye"       "pacoramon"      
## [41] "neslihanky"      "wang_minjie"     "PipingHotData"   "Jack36161714"   
## [45] "KenButler12"     "xeroluck"        "rstats4ds"       "francisco_yira"

One thing you may note is that I don’t use the query argument, I just pull the default parameters – again see Jessica’s posts for a more sophisticated example as well as descriptions of the steps above.

  1. I will warn that it took me an embarrassing amount of time to catch a slight change in the Twitter API between now and when Jessica wrote her post see note on expansions.↩︎

  2. Think you need the app within a project, not just a standalone app for access to V2. The Creating a Twitter app section of Authentication with rtweet is also a helpful tutorial for getting started here. However the documentation there does not indicate the need to create a project first, however {rtweet} uses V1, not V2.↩︎

  3. Project has a local .Renviron file.↩︎