-
Notifications
You must be signed in to change notification settings - Fork 65
HTTP API
Rserve has a built-in server that supports the HTTP protocol. It can be enabled by setting one of more or http.port
, https.port
or http.tls.port
options (lattew two for HTTP+TLS = https).
This document describes the API which maps the HTTP request to a function call in R and then maps the returned value to a response.
The server accepts a HTTP request and maps it into a call in R of the form:
try(.http.request(url, query, body, headers), silent=TRUE)
with the following arguments:
-
url: string, path of the request (yes, sorry, a historical misnomer)
-
query:
NULL
(if there is no query string) or a named character vector with each element corresponding to one query string -
body:
NULL
(if there is no body), named character vector (if the body is of typeapplication/x-www-form-urlencoded
) or a raw vector (all other cases) with"content-type"
attribute containing theContent-type
header entry (if present).NOTE: if
http.raw.body
Rserve option is enabled then the body is always sent as a raw vector and never decoded.For helper functions to parse multi-part body contents see
FastRWeb::parse.multipart(list(body=body, c.type=attr(body, "content-type"), c.length=length(body)))
-
headers:
NULL
(if there are no headers) or a raw vector of all header entries.
The function is expected to return the result which will be turned into a HTTP response.
The result is expected to be a list in the form
list(payload[, content-type[, headers[, status code]]])
with following entries (by index, not name):
-
payload: either a character vector of length one or a raw vector. If the vector is named
file
then the contents of the file is served instead of the string itself (e.g.:list(file="foo.png", "image/png")
will serve the image file contents). -
content-type: optional, string, defaults to
"text/html"
if not specified (or ifNULL
) -
headers: optional, character vector with each element one line of the headers. It may not contain
"Content-type"
nor"Content-length"
as those are synthesized by Rserve. -
code: optional, status code (defaults to
200
)
If the result is a character vector of length one (e.g., if try()
catches an error), it is returned as status code 500 with the string as payload. Any other return value is invalid and will yield 500 Invalid response from R
HTTP response.
NOTE: this API is identical to the R builtin HTTP server (since I used the same code) with the exception that the builtin server uses tools::.httpd.handlers.env
handlers per path instead of a fixed .http.request
entry point.
It is possible to re-map FastRWeb run()
API into Rserve API simply by setting
.http.request <- FastRWeb:::.http.request
For a more comprehensive API aimed at web app developers, see the RestRserve project which is a layer on top of Rserve