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:



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


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

When I run:

r = plumb("main.R")

I get expected output:

[1] "I am sourced"

Then I run:


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

pr <- plumb("main.R")
prf <- plumb("functions.R")
pr$mount("/functions/", prf)

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 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 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.