1 Load libraries

suppressWarnings(library(jsonlite))
suppressWarnings(library(XML))

2 Overriding “+”.

(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)
    }
}

3 Writing global variable.

Get your key from http://developer.nytimes.com/docs and assign your key to variable article_key.

article_key <- {your-API-key}

4 Writing reusable search function.

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)
  }

}