Search code examples
rlistapipastehttr

Pasting list inside a URL using R


I am playing around with some APIs and have a simple question. How do I paste a comma separated list after = in the URL below instead of writing everything manually?

library(httr)

X <- GET("url/?query=")

In other words, given my list L I'd like to end up with:

X <- GET("url/?query=a,b,c,d")

Thanks!

Update L looks like:

> dput(L)
list("a","b","c","d")

Solution

  • This is a much safer and saner way to build/pass query strings:

    library(httr)
    
    res <- GET(url = "http://httpbin.org/get",
               query = list(
                 query = paste0(list("a","b","c","d"), collapse=",")
               ))
    
    str(content(res, as="parsed"))
    ## List of 4
    ##  $ args   :List of 1
    ##   ..$ query: chr "a,b,c,d"
    ##  $ headers:List of 5
    ##   ..$ Accept         : chr "application/json, text/xml, application/xml, */*"
    ##   ..$ Accept-Encoding: chr "gzip, deflate"
    ##   ..$ Connection     : chr "close"
    ##   ..$ Host           : chr "httpbin.org"
    ##   ..$ User-Agent     : chr "libcurl/7.51.0 r-curl/2.3 httr/1.2.1"
    ##  $ origin : chr "50.252.233.22"
    ##  $ url    : chr "http://httpbin.org/get?query=a%2Cb%2Cc%2Cd"