Static file server in R

{plumber} is (always) the answer

r
plumber
api
Author

Josiah Parry

Published

June 24, 2024

Plumber, ambiorix, and opencpu are the keys to putting R into production.

Sometimes all an API needs to do is statically serve files. Making a static file server with R is insanely easy.

For this example, I have a folder called /public which I want to serve files from at the API path /static.

To do this we create a plumber API using the pr_static() function or #* @assets if using the other plumber declaration format.

Making the file server

library(plumber)

pr() |>
  pr_static("/static", "./public") |>
  pr_run()

calling the file server

We can call this api using a GET request:

library(httr2)

iris_csv <- request("http://127.0.0.1:3000/static/iris.csv") |>
  req_perform() |>
  resp_body_string()

readr::read_csv(iris_csv)
Rows: 150 Columns: 5
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): Species
dbl (4): Sepal.Length, Sepal.Width, Petal.Length, Petal.Width

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# A tibble: 150 × 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <chr>  
 1          5.1         3.5          1.4         0.2 setosa 
 2          4.9         3            1.4         0.2 setosa 
 3          4.7         3.2          1.3         0.2 setosa 
 4          4.6         3.1          1.5         0.2 setosa 
 5          5           3.6          1.4         0.2 setosa 
 6          5.4         3.9          1.7         0.4 setosa 
 7          4.6         3.4          1.4         0.3 setosa 
 8          5           3.4          1.5         0.2 setosa 
 9          4.4         2.9          1.4         0.2 setosa 
10          4.9         3.1          1.5         0.1 setosa 
# ℹ 140 more rows

Alternative plumber format

#* @assets ./public /static
list()