source("model.R")R App & API
This chapter builds the R version of Python App & API. I’ll launch a vetiver API in one session and send predictions to it from a Shiny app (using httr2) in another.
I isolated development for the R Shiny app and API for lab 3 into separate app/ and api/ directories:
_labs/lab03/R
├── api
│ ├── api.Rproj
│ ├── mod-api.R
│ ├── model.R
│ ├── models/
│ ├── my-db.duckdb
│ ├── README.md
│ ├── renv
│ └── renv.lock
├── app
│ ├── app-api.R
│ ├── app.Rproj
│ ├── README.md
│ ├── renv
│ └── renv.lock
├── eda-db.qmd
├── r-data-load.R
└── R.Rproj- 1
-
vetivermodel API
- 2
-
shinyapplication
- 3
-
EDA of
palmerpenguinsdata usingdplyrandggplot2
- 4
-
Load
palmerpenguinsdata intoduckdb
Model
The API reads the model from a pins board in models/, and that board doesn’t exist until we train and pin the model. Open a RStudio/Positron session from _labs/lab03/R/api/ and run model.R:
This is the same linear model from R processing layer, with three changes:
- The query drops rows with missing values and keeps
bill_length_mmbetween 30 and 60, so 333 of the 344 rows remain.
lm()takesspeciesandsexas factors and creates the dummy variables itself (lab 2 built them withdummy_cols()).
- As a result, the
vetiverprototype has three columns, and the API expectsspeciesandsexas strings.
Loaded 333 observations from DuckDB
=== Model Training Complete ===
Formula:
body_mass_g ~ bill_length_mm + species + sex
Coefficients:
(Intercept) bill_length_mm speciesChinstrap speciesGentoo
2169.26972 32.53689 -298.76553 1094.86739
sexmale
547.36692
===============================
Vetiver prototype (API will expect this format):
# A tibble: 0 × 3
# ℹ 3 variables: bill_length_mm <dbl>, species <fct>, sex <fct>
Creating new version '20261127T072151Z-d2aea'
Writing to pin 'penguin_model'
✓ Model trained and pinned successfully
Model name: penguin_model
Pin location: ./models/penguin_modelThe coefficients match lab 2. We can confirm the board exists by listing the models/ folder:
fs::dir_tree("models")models
└── penguin_model
└── 20261127T072151Z-d2aea
├── data.txt
└── penguin_model.rdsAPI
In a RStudio/Positron session opened from _labs/lab03/R/api/, the mod-api.R file contains the following (I’ve removed the sections that print the model info):
# pkgs
library(vetiver)
library(pins)
# connect to lab03 model board ----
model_board <- pins::board_folder("models/")
# read pinned vetiver model ----
v <- vetiver::vetiver_pin_read(model_board, "penguin_model")
# create plumber API ----
app <- plumber::pr() |> vetiver::vetiver_api(v) Start the API
Run the API below in its own session; pr_run() blocks the console, so we’ll launch the app from a second session.
app |> plumber::pr_run(port = 8080, host = "127.0.0.1")Now we have a working API! We’ll explore the UI in the sections below. Let’s launch the app.1
App
Open a separate RStudio/Positron session from _labs/lab03/R/app/ and launch the app with app-api.R. I’ve made a few changes to the UI layout, so when I launch the app, I see the following:
View the UI changes below:
show/hide UI changes to app-api.R
api_url <- "http://127.0.0.1:8080/predict"
ui <- page_sidebar(
title = "Penguin Mass Predictor",
theme = bs_theme(bootswatch = "sketchy"),
sidebar = sidebar(
sliderInput(inputId = "bill_length",
label = "Bill Length (mm)",
min = 30,
max = 60,
value = 45,
step = 1),
selectInput(inputId = "sex",
label = "Sex",
choices = c("Male", "Female"),
selected = "Male"),
selectInput(
inputId = "species",
label = "Species",
choices = c("Adelie", "Chinstrap", "Gentoo"),
selected = "Adelie"),
actionButton(
inputId = "predict",
label = "Predict",
class = "btn-primary")
),
layout_columns(
card(
card_header("Penguin Parameters"),
card_body(
verbatimTextOutput("vals")
)
),
card(
card_header("Predicted Mass"),
card_body(
value_box(
showcase_layout = "left center",
title = "Grams",
value = textOutput("pred"),
showcase = bs_icon("graph-up"),
max_height = "200px",
min_height = "200px",
)
)
),
col_widths = c(7, 5)
)
)Original error
In the original server, vals() returned a list() (the full code is in Original App Code at the end of this chapter). With that list, clicking Predict produced the following error:
Warning: Error in httr2::req_perform:
HTTP 500 Internal Server Error.In the API session, we also see an error:
<error/rlang_error>
Error in `hardhat::validate_column_names()`:
! `data` must be a data frame or a matrix, not a list.Both errors point to the same problem. httr2::req_body_json() sends the list as a single JSON object, but the vetiver API expects a data frame or a matrix.
We can fix this in the application server by changing the format of the values sent to the API.
Reactive values
The API error tells us data must be a data frame or a matrix. We’ll convert vals() to a single row data.frame with the columns the model was trained on: bill_length_mm, species, and sex (lowercase, to match the factor levels in the data).
vals <- reactive({
data.frame(
bill_length_mm = input$bill_length,
species = input$species,
sex = tolower(input$sex)
)
})Predictions
The pred() reactive sends vals() to the API and returns only response$.pred[[1]].
pred <- reactive({
tryCatch({
showNotification("Predicting penguin mass...",
type = "default", duration = 10)
request_data <- vals()
response <- httr2::request(api_url) |>
httr2::req_method("POST") |>
httr2::req_body_json(request_data, auto_unbox = FALSE) |>
httr2::req_perform() |>
httr2::resp_body_json()
showNotification("✅ Prediction successful!",
type = "default", duration = 10)
response$.pred[[1]]
}, error = function(e) {
error_msg <- conditionMessage(e)
if (grepl("Connection refused|couldn't connect", error_msg, ignore.case = TRUE)) {
user_msg <- "API not available - is the server running on port 8080?"
} else if (grepl("timeout|timed out", error_msg, ignore.case = TRUE)) {
user_msg <- "Request timed out - API may be overloaded"
} else {
user_msg <- paste("API Error:", substr(error_msg, 1, 50))
}
showNotification(paste("❌", user_msg), type = "warn", duration = 10)
paste("❌", user_msg)
})
}) |>
bindEvent(input$predict, ignoreInit = TRUE)- 1
-
api_urlis “http://127.0.0.1:8080/predict”
- 2
-
request_datais a single row data frame, soreq_body_json()sends it as a JSON array with one object per row (the formatvetiverexpects).auto_unbox = FALSEdoesn’t change the JSON for a data frame.
R API Request/Response Flow
The sections below cover the httr2 functions used in the Shiny API app. The diagram shows how each function hands its result to the next:
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace'}}}%%
flowchart TD
A(["<strong>request()</strong><br>sets the URL"]) --> B("<strong>req_method()</strong><br>sets the verb (POST)")
B --> C("<strong>req_body_json()</strong><br>adds vals() as JSON")
C --> D("<strong>req_perform()</strong><br>sends the request")
D --> E["vetiver API<br>/predict"]
E --> F[/"JSON response"/]
F --> G("<strong>resp_body_json()</strong><br>parses JSON into an R list")
style A fill:#5B8C5A,stroke:#000000,stroke-width:1px,color:#ffffff
style B fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style C fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style D fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
style E fill:#485466,stroke:#000000,stroke-width:1px,color:#ffffff
style F fill:#D2562B,stroke:#000000,stroke-width:1px,color:#ffffff
style G fill:#2A6F77,stroke:#000000,stroke-width:1px,color:#ffffff
The request()
httr2::request() creates the initial request object that all other functions will modify:
Stores the base URL
Uses
GETby default (andPOSTonce a body is added)Initializes empty headers, query parameters, and body
Returns a modifiable request object
# creates a base request with URL
response <- httr2::request(api_url)req_method()
verb specification
httr2::req_method() specifies which HTTP method to use for the request.
GET: Retrieve data (no body allowed)POST: Send new data (body allowed)PUT: Update existing data (body allowed)DELETE: Remove data (usually no body)
response <- httr2::request(api_url) |>
httr2::req_method("POST") # sending datareq_body_json()
request body
httr2::req_body_json() converts R objects to JSON and includes them in the request body.
Converts R
lists/data.frames to JSON formatSets
Content-Type: application/jsonheader automaticallyIncludes the JSON in the HTTP request body
Used primarily with
POST/PUTrequests
vals <- reactive({
data.frame(
bill_length_mm = input$bill_length,
species = input$species,
sex = tolower(input$sex)
)
})
request_data <- vals()
response <- httr2::request(api_url) |>
httr2::req_method("POST") |> # sending data
httr2::req_body_json(request_data, auto_unbox = FALSE)req_perform()
execute request
httr2::req_perform() actually sends the HTTP request to the server and returns a response:
What happens:
1. Combines all request components (method, headers, query, body)
2. Opens network connection to server
3. Sends HTTP request
4. Waits for server response
5. Returns response object for processing
response <- httr2::request(api_url) |>
httr2::req_method("POST") |> # sending data
httr2::req_body_json(request_data, auto_unbox = FALSE) |>
httr2::req_perform()resp_body_json()
JSON response parsing
httr2::resp_body_json() parses JSON response body into R objects.
Converts JSON arrays to R vectors/lists
Converts JSON objects to R named lists
Handles nested JSON structures
Automatically converts data types (numbers, booleans, strings)
response <- httr2::request(api_url) |>
httr2::req_method("POST") |> # sending data
httr2::req_body_json(request_data, auto_unbox = FALSE) |>
httr2::req_perform() |>
httr2::resp_body_json()Verify
Now when we launch the app, the preview of the parameters is in a data.frame (not a list):
When we click Predict, we see notifications and the value is returned:
Back in the API
If we return to the plumber UI, we can click on Return predictions from model using 3 features. We change the JSON values to match our parameters in the app, then click TRY:
And we can compare the response to the value we saw in the app:
The diagram below follows one prediction from the Shiny app through the plumber API to the vetiver model:
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace'}}}%%
sequenceDiagram
participant Customer as Shiny<br>App
participant Waiter as Plumber<br>API
participant Kitchen as Vetiver<br>Model
Customer->>Waiter: Prediction request:<br>bill_length=45,<br>species=Adelie, sex=male
Waiter->>Kitchen: Prepare data
Kitchen->>Waiter: Perform prediction
Waiter->>Customer: Returns prediction:<br>4180.8 grams
Finishing touches
To keep the R environment in each directory self-contained and reproducible, we should initialize an renv project in each folder.
renv::init()This results in the following files:
R/api/ files
_labs/lab03/R/api
├── README.md
├── api.Rproj
├── mod-api.R
├── model.R
├── models
│ └── penguin_model
├── my-db.duckdb
├── renv
│ ├── activate.R
│ ├── library
│ ├── settings.json
│ └── staging
└── renv.lockR/app/ files
_labs/lab03/R/app
├── README.md
├── app-api.R
├── app.Rproj
├── renv
│ ├── activate.R
│ ├── library
│ ├── settings.json
│ └── staging
└── renv.lockRecap
The
vetiverAPI only takes a few lines in R: read the pinned model withvetiver_pin_read(), pass it tovetiver_api()on aplumberrouter, and start it withpr_run()on port 8080.The original app failed with an
HTTP 500error because it sent the inputs as a JSON list, and thevetiverAPI expects a data frame or matrix. Buildingvals()as a single rowdata.frame(withspeciesandsexas strings) fixed the request.The
httr2request is a pipeline:request()sets the URL,req_method()sets the verb,req_body_json()attaches the data,req_perform()sends it, andresp_body_json()parses the response. Wrapping that pipeline intryCatch()turns connection failures and timeouts into notifications instead of a crashed app.
In plumber we’ll rebuild this API with custom handler functions, input validation, and batch predictions.
Original App Code
To view the original code in app-api.R, expand the section below:
Expand to view the original app-api.R
library(shiny)
api_url <- "http://127.0.0.1:8080/predict"
ui <- fluidPage(
titlePanel("Penguin Mass Predictor"),
# Model input values
sidebarLayout(
sidebarPanel(
sliderInput(
"bill_length",
"Bill Length (mm)",
min = 30,
max = 60,
value = 45,
step = 0.1
),
selectInput(
"sex",
"Sex",
c("Male", "Female")
),
selectInput(
"species",
"Species",
c("Adelie", "Chinstrap", "Gentoo")
),
# Get model predictions
actionButton(
"predict",
"Predict"
)
),
mainPanel(
h2("Penguin Parameters"),
verbatimTextOutput("vals"),
h2("Predicted Penguin Mass (g)"),
textOutput("pred")
)
)
)
server <- function(input, output) {
# Input params
vals <- reactive(
list(
bill_length_mm = input$bill_length,
species_Chinstrap = input$species == "Chinstrap",
species_Gentoo = input$species == "Gentoo",
sex_male = input$sex == "Male"
)
)
# Fetch prediction from API
pred <- eventReactive(
input$predict,
httr2::request(api_url) |>
httr2::req_body_json(vals()) |>
httr2::req_perform() |>
httr2::resp_body_json(),
ignoreInit = TRUE
)
# Render to UI
output$pred <- renderText(pred()$predict[[1]])
output$vals <- renderPrint(vals())
}
# Run the application
shinyApp(ui = ui, server = server)





