Introduction to Plumber and REST
Understand REST principles and annotate R functions as API endpoints.
What Is a REST API?
A REST (Representational State Transfer) API is a web service that exposes data and operations via HTTP. Key principles:
- Stateless: each request contains all information needed; no server-side session.
- Resource-oriented: endpoints represent resources (
/users,/predictions). - Standard HTTP verbs: GET (read), POST (create), PUT (update), DELETE (remove).
- JSON: the standard data format for request and response bodies.
# REST API concepts in HTTP terms:
# GET /api/model/predict?x=5 -> read a prediction
# POST /api/model/train -> create a new model
# GET /api/data/summary -> read data summary
# DELETE /api/cache/flush -> remove cached results
# Plumber maps R functions to these HTTP endpoints
cat('REST: stateless, resource-oriented, JSON responses')plumber Annotation Syntax
plumber uses special comment annotations starting with #* to define API endpoints. Place an annotation directly above the R function that handles the endpoint. The function arguments map to request parameters; the return value becomes the JSON response body.
# plumber.R
library(plumber)
#* @get /ping
function() {
list(status = 'ok', time = Sys.time())
}
#* @get /add
#* @param a:int First number
#* @param b:int Second number
function(a, b) {
list(result = as.integer(a) + as.integer(b))
}All lessons in this course
- Introduction to Plumber and REST
- Creating GET and POST Endpoints
- Authentication and API Security
- Deploying Plumber APIs to Production