Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add REST API example with plumber #260

Merged
merged 6 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
Loading