Search code examples
rhttrplumber

How to do the plumber::plumb(file = 'mypath') in httr?


I am struggling to find a solution that httr can do the same thing as plumber in R. In plumber here's the code that works:

1). Create a script hello_world_plumber.R

#' @post /hello_world
hi <- function(name) {
  return(paste0('Hello ', name, '!'))
}

2). In another script:

pr <-  plumb(file = '~/hello_world_plumber.R')
pr$run(swagger = F)

Starting server to listen on port 5852
Running the swagger UI at http://127.0.0.1:5852/__swagger__/

3). In the terminal

curl -s --data 'Matt' http://127.0.0.1:5852/hello_world
Out: Hello Matt!

Solution

  • plumber is built on top of the httpuv library to help you define an API quickly with a few decorations.

    httr package is to send http queries via the curl command.

    So httr is like a client and plumber is your server. That's why there is more downloads. There is way more Chrome/Firefox download than Nginx/Apache, it is just the nature of the tools.

    You could achieve the same thing without plumber just using httpuv if you don't care about decoration, async, query string and body parsing, openapi and other goodies. it is pretty bare though.

    runServer("127.0.0.1", 8477,
      list(
        call = function(req) {
          list(
            status = 200L,
            headers = list(
              'Content-Type' = 'text/html'
            ),
            body = "Hello world!"
          )
        }
      )
    )
    

    There are multiple plumber alternatives too, RestRserve, OpenCPU to name a few.

    Depending on your use case, you select what works best for you. If you need any plumber help, feel free to ask. I don't see it going away soon as it has been incorporated into RStudio IDE and I think it's decoration structure a la roxygen2 makes it simple to adopt.