Last active
June 27, 2017 09:13
-
-
Save etiennekintzler/d51fa61068294819c1de61b723942b96 to your computer and use it in GitHub Desktop.
Application-only authentication on Twitter API using R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In order to use application-only authentification, one will need a consumer key and consumer secret. | |
# For more information regarding this mode of authentification : https://dev.twitter.com/oauth/application-only | |
library(httr) | |
library(base64enc) | |
# 1. Encode consumer key and secret | |
consumer_key <- "" | |
consumer_secret <- "" | |
enc_consumer_key <- URLencode(URL = consumer_key) | |
enc_consumer_secret <- URLencode(URL = consumer_secret) | |
key_secret <- sprintf(fmt = "%s:%s", enc_consumer_key, enc_consumer_secret) | |
# Encoding consumer key and secret using Base64 encoding. key_secret must be convert to raw vector | |
enc_key_secret <- base64enc::base64encode(what = charToRaw(key_secret)) | |
# 2. Obtaining bearer token using HTTP POST request | |
headers_connect <- c("Host" = "api.twitter.com", | |
"Authorization" = sprintf("Basic %s", enc_key_secret), | |
"Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8", | |
"Content-Length" = "29", | |
"Accept-Encoding" = "gzip") | |
connect_app <- httr::POST(url = "https://api.twitter.com/oauth2/token", | |
config = httr::add_headers(headers_connect), | |
body = "grant_type=client_credentials") | |
bearer_token <- httr::content(connect_app)$access_token | |
# 3. Authentificate API requests using the bearer token. Example of GET request : Timeline of twitterapi | |
# Defining headers for GET | |
headers_get <- c(Host = "api.twitter.com", | |
"User-agent"= "", | |
"Authorization" = paste0("Bearer ", bearer_token)) | |
# Defining request name. Available requests can be found on : https://dev.twitter.com/rest/reference | |
request_name <- "statuses/user_timeline" | |
# Defining parameters | |
parameters <- list(screen_name = "twitterapi", count = 100) | |
query <- lapply(parameters, function(x) URLencode(as.character(x))) | |
results <- httr::GET(url = paste0("https://api.twitter.com/1.1/", request_name, ".json"), | |
query = query, | |
config = httr::add_headers(headers_get)) | |
# Displaying status code. 200 means successful request | |
httr::status_code(results) | |
# Displaying the results, in list format. | |
httr::content(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment