Site icon R-bloggers

R Access to Twitter’s V2 API

[This article was first published on rstats on Bryan Shalloway's Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 tweet. (Though I will warn that it took me an embarrassing amount of time to catch a slight typo in the tutorial1.)

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 my initial announcement of the pwiser package.

Compute all pairwise ratios, t-tests, distance metrics, or whatever using {pwiser} a new 📦 I’m writing with @CarloooMedina for applying arbitrary functions on pairwise combinations of columns using a dplyr::across() style syntax: https://t.co/DTXElWbuuX #rstats #tidyverse pic.twitter.com/wrMzX5mOYx

— Bryan Shalloway (@brshallo) May 16, 2021

First you need to:

  1. Apply for a Twitter developer account.
  2. Create a project
  3. Create an app within that project (pretty sure you need the app within a project, not just a standalone app)

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 environment2.

library(rjson)
require(httr)
require(jsonlite)
require(dplyr)
library(purrr)

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 %>% 
  purrr::map_chr("username")
##  [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. At least that was there at the time of this writing↩︎

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

To leave a comment for the author, please follow the link and comment on their blog: rstats on Bryan Shalloway's Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.