Skip to content

Commit

Permalink
Add REST API example with plumber (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
ellieko committed Jul 30, 2024
1 parent 46ec9af commit 5d374c9
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
9 changes: 9 additions & 0 deletions examples/plumber/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM rstudio/plumber

WORKDIR /app

COPY . /app

EXPOSE 80

ENTRYPOINT ["Rscript", "main.R"]
3 changes: 3 additions & 0 deletions examples/plumber/main.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
library(plumber)
pr <- plumb("rest_controller.R")
pr$run(port = 80, host = "0.0.0.0")
Binary file added examples/plumber/plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions examples/plumber/rest_controller.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#* @apiTitle Plumber Example API
#* @apiDescription This API allows users to interact with a linear regression model predicting iris petal length from petal width.
#* It provides endpoints for health checks, predictions, and visualizations of the model fit.

# Prepare the model
dataset <- iris
model <- lm(Petal.Length ~ Petal.Width, data = dataset)

#* Health Check - Returns the API status and the current server time
#* @get /health-check
function() {
list(
status = "The API is running",
time = Sys.time()
)
}

#* Predict petal length - Returns a predicted petal length for a given petal width using a linear regression model
#* @param petal_width Numeric: Width of the petal for which length is to be predicted
#* @post /predict_petal_length
function(petal_width) {
input_data <- data.frame(Petal.Width = as.numeric(petal_width))
prediction <- predict(model, input_data)
list(petal_width = petal_width, predicted_petal_length = prediction)
}

#* Plot regression line and data points - Displays a scatter plot of the data and the regression line, illustrating the model fit
#* @serializer png
#* @get /plot_regression
function() {
plot(dataset$Petal.Width, dataset$Petal.Length,
xlab = "Petal Width", ylab = "Petal Length",
main = "Linear Model Fit: Petal Length vs Petal Width"
)
abline(model, col = "red") # Adds the regression line in red
}

0 comments on commit 5d374c9

Please sign in to comment.