Search code examples
pythonrurlresponseurllib3

which R package provides functionality similar to pythons urllib


My task is to port a snipped of python code which uses python urllib to R. This is the entire python code:

import urllib.parse
import urllib.request

url = "https://www.uniprot.org/uploadlists/"

params = {
  "from": "ACC+ID",
  "to": "ENSEMBL_ID",
  "format": "tab",
  "query": "P40925 P40926 O43175 Q9UM73 P97793"
}

data = urllib.parse.urlencode(params)
data = data.encode("utf-8")
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as f:
  response = f.read()
print(response.decode("utf-8"))

I am not to keen to use paste and paste0 to build url's manually in R. What I did find is the R urltools package. But it does not help me with url-encoding the data as urllib.parse.urlencode does.

What would be the R package to use to re-implement the python code? Or should I use reticulate?

Thank you


Solution

  • I think httr should get the job done:

    url <- "https://www.uniprot.org/uploadlists/"
    
    params = list(
      from = "ACC+ID",
      to = "ENSEMBL_ID",
      format = "tab",
      query = "P40925 P40926 O43175 Q9UM73 P97793"
    )
    
    r <- httr::POST(url, body = params, encode = "form")
    cat(httr::content(r))
    #> No encoding supplied: defaulting to UTF-8.
    #> From To
    #> P40925   ENSG00000014641
    #> P40926   ENSG00000146701
    #> O43175   ENSG00000092621
    #> Q9UM73   ENSG00000171094
    #> P97793   ENSMUSG00000055471
    

    Created on 2019-09-02 by the reprex package (v0.3.0.9000)