Create a simple web server with plumber

The plumber package is great for creating APIs in R, but it has a coupe of lesser known tricks up it’s sleeve and I wanted to talk about one of those today.

In the modern web-based world, you sometimes just need a simple web server to serve HTML pages or other content across the network.

Fortunately, plumber can help. The goal here is to take a directory of content, such as HTML, CSS and javascript and create a web server that will serve that directory of content to users on the same network.

In this example, all of the files we’d like to be accessible via our web server are in a directory called www which is in the same directory as our plumber.R file.

The contents of plumber.R:


#* @apiTitle Plumber Web server

#* serve static content
#* @assets ./www/

When run via the ‘Run API’ button at the top of the editor pane in the RStudio IDE, this creates a web server that serves everything in your ./www/ directory.

You can access your web server at the default URL of http://localhost:8686/public/<filename> as in the screenshot above.

I’ve used ./www/ as an example here, but you should use a path to the files that you’d like to serve.

In this example, I’ve used a relative path, ./www/, which means it’s the www directory that is in the current working directory. This is fine if you’re running the code on your local machine, but if you wanted to publish this to RStudio Connect, you’d need to specify an absolute path, for example /data/www.

Remember that if you were to publish something like this to Connect it can be a little trickier to figure out the URL. The best thing to do is to set a custom “Content URL” (This example uses ws), so you end up with a URL that looks something like this: https://<CONNECT_SERVER_URL>/ws/public/<FILENAME>.

Plumber has lots more lesser-known features that are worth checking out, but that’s all for now.

Happy web serving!