Functions within a sourced file are not accessible as Plumber API endpoints

I cannot get functions from another (sourced) file to be accessible through the API.

My setup is very basic:

main.R:

source("./functions.R")

#* Echo back the input
#* @param msg The message to echo
#* @get /echo
function(msg=""){
  list(msg = paste0("The message is: '", msg, "'"))
}

functions.R:

print("I am sourced")
#* Return "hello world"
#* @get /hello
function(){
  "hello world"
}

When I run:

r = plumb("main.R")

I get expected output:

[1] "I am sourced"

Then I run:

r$run(port=8000)

And the /echo endpoint is accessible, but the /hello one is not, returning 404 - Resource Not Found.

Any idea, how to include the file properly to get it accessible through the API?

This is not how plumber currently works. But you could achieve something similar by removing source line and to do something like this. This does not work with the CRAN version 0.4.6 but the bug has been resolved in the master branch 0.4.7.9000.

devtools::install_github("rstudio/plumber")
pr <- plumb("main.R")
prf <- plumb("functions.R")
pr$mount("/functions/", prf)
pr$run()

What you can do right now is plumb each file to a different router and then add them on top of each other. No need for source.

See https://www.rplumber.io/docs/programmatic-usage.html#mount-static for documentation

Plumber starts by parsing the file you sent to the plumb method line by line to extract information about your endpoints. It then execute all lines it could not match with a known decoration (your source line in this case). plumb method only allows for one file to be parsed at a time. There is no reason why it could not just paste the content of multiple files together and then parse it but I think it would not look great? Anyway...

1 Like

See also https://github.com/rstudio/plumber/issues/533 for another example how to achieve it, adding to the @meztez 's solution/explanation.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.