Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206531

R: passing API request as an argument to a function

$
0
0

What is the correct way to form an API request which can be passed to a function as an argument? The request is intended to be constructed inside another function with specific arguments.

An example of the request is the following:

library(httr)
GET("http://httpbin.org/get")

What I would like to have is the two functions:

  • one for constructing the request, and
  • the other is for sending it.

The idea is to construct the request based on multiple parameters, including POST/GET, headers, tokens, and then to put it to another function, which is responsible for safe sending of the request.

What I've tried
A simplified example, which shows the required structure (though it does not work properly).

# Function for sending the API request
fn <- function(request) {
  eval(request)
}

# Top function for constructing the request to be sent
fntop <- function(url, type) {
  url <- sprintf("%s%s", url, type)
  my_request <- expression(GET(url))

  fn(my_request)
}

The first function works fine when it receives the direct request.

fn(GET("http://httpbin.org/get"))

However, the same function doesn't work when it is called from the other function with the request containing variables

fntop(url = "http://httpbin.org/",
      type = "get")
# Error in as.character(url) : 
#  cannot coerce type 'closure' to vector of type 'character'

How is it possible to pass API request containing variables as an argument into a function?


Viewing all articles
Browse latest Browse all 206531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>