suppressWarnings(library(jsonlite))
suppressWarnings(library(XML))
(Since I am from Java background) overriding “+”, so we can use it for string concatenation.
"+" = function(x,y)
{
if(is.character(x) || is.character(y))
{
return(paste(x , y, sep=""))
}
else
{
.Primitive("+")(x,y)
}
}
Get your key from http://developer.nytimes.com/docs and assign your key to variable article_key.
article_key <- {your-API-key}
Writing reusable function to serach most popular function on nytimes.com. if you need to debug quickly then paste below URL in browser http://api.nytimes.com/svc/mostpopular/v2/mostemailed/all-sections/1.json?api-key={your-API-KEY}
#http://api.nytimes.com/svc/mostpopular/v2/mostemailed/all-sections/30.json?api-key={your-api-key}
#resource_type =>mostemailed | mostshared | mostviewed
#time_period=>Number of days:1 | 7 | 30,Corresponds to a day, a week or a month
searchNY_Most_Popular_Article <- function(resource_type,time_period,format)
{
#Pending - validate each argument variable
baseURL<-"http://api.nytimes.com/svc/mostpopular/v2/"
URL <- baseURL+resource_type+"/all-sections/"+time_period+"."+format+"?api-key="+article_key
if(format=='json')
{
req <- fromJSON(URL)
return (req$results)
}
else
{
xmldoc<-xmlParse(URL)
return (xmldoc)
}
}
xmldoc<-searchNY_Most_Popular_Article('mostemailed',1,'xml') ##XML search
jsondoc<-searchNY_Most_Popular_Article('mostemailed',1,'json') ##json search
colnames(jsondoc)
## [1] "url" "count_type" "column" "section"
## [5] "byline" "title" "abstract" "published_date"
## [9] "source" "des_facet" "org_facet" "per_facet"
## [13] "geo_facet" "media"
jsondocDF<-data.frame(jsondoc)
mostpopular<-head(jsondocDF,1)
mostpopular$title
## [1] "13 Questions to Ask Before Getting Married"
mostpopular$abstract
## [1] "There are certain intimate and awkward topics couples should discuss before the wedding <U+0097> unless you prefer to be surprised years later."