Building APIs with Plumber + POST
stat133-api.R)plumber::plumb() to load the scriptpr_run() to start the API server# A tibble: 1,924,665 × 5
year sex name n prop
<dbl> <chr> <chr> <int> <dbl>
1 1880 F Mary 7065 0.0724
2 1880 F Anna 2604 0.0267
3 1880 F Emma 2003 0.0205
4 1880 F Elizabeth 1939 0.0199
5 1880 F Minnie 1746 0.0179
6 1880 F Margaret 1578 0.0162
7 1880 F Ida 1472 0.0151
8 1880 F Alice 1414 0.0145
9 1880 F Bertha 1320 0.0135
10 1880 F Sarah 1288 0.0132
# ℹ 1,924,655 more rows
Question: Sketch ~7-9 lines of code to create a new endpoint /babynames that takes a param babyname and returns a data frame filtered on that name.
02:00
@serializer json (default)@serializer png@serializer jpeg@serializer html@serializer contentType list(type="image/svg+xml")#* Plot timeseries of a name from the babynames dataset
#* @param babyname The name to plot (required)
#* @get /plot
#* @serializer png
function(babyname = "Mary"){
library(babynames)
library(dplyr)
library(ggplot2)
myData <- babynames |>
filter(name == babyname) |>
group_by(year) |>
summarize(n = sum(n), .groups = "drop")
p <- ggplot(myData, aes(x = year, y = n)) +
geom_line() +
labs(title = paste("Popularity of", babyname, "over time"),
x = "year",
y = "Count") +
theme_bw()
print(p)
}Let’s improve the clarify by returning an SVG (support vector graphics) image instead of PNG.
#* Plot timeseries of a name from the babynames dataset
#* Returns an SVG image viewable directly in browser
#* @param babyname The name to plot (required)
#* @get /plot
#* @serializer contentType list(type="image/svg+xml")
function(babyname = "Mary"){
library(babynames)
library(dplyr)
library(ggplot2)
library(svglite)
myData <- babynames |>
filter(name == babyname) |>
group_by(year) |>
summarize(n = sum(n), .groups = "drop")
p <- ggplot(myData, aes(x = year, y = n)) +
geom_line() +
labs(title = paste("Popularity of", babyname, "over time"),
x = "year",
y = "Count") +
theme_bw()
tf <- tempfile(fileext = ".svg")
svglite::svglite(tf, width = 7, height = 5)
print(p)
dev.off()
paste(readLines(tf, warn = FALSE), collapse = "\n")
}