Automated testing of a Plumber API deployed on RStudio COnnect

Hi everyone,

I have an API that I am developping on my computer then deploying on the RStudio connect server.

I have the following code to make sure it works when deployed on my computer.

library(testthat)
library(httr)
root_path <- "http://localhost"

api1 <- callr::r_bg(
function() {
pr <- plumber::plumb(here::here("plumber.R"))
pr$run(port = 8000)
}
)

Sys.sleep(5)

test_that("API is alive", {
expect_true(api1$is_alive())
})

test_that("echo endpoint works", {

Send API request

r <- httr::GET(root_path, port = 8000, path = "echo", query = list(msg = "Hello World"))

Check response

expect_equal(r$status_code, 200)
expect_equal(httr::content(r, encoding = "UTF-8"), list(msg = list("The message is: 'Hello World'")))
})

I would like to be able to run a similar test on the API when deployed on my RStudio connect server, but I'm not sure how to call it since I would need to pass it my username/password.

For the sake of argument let's say my endpoint on the server is located at
https://rstudiotest.mycompany.com/myapi/echo

Hi, the API authentication in RStudio Connect is done via an API Key, here is the link to the article: API Keys - RStudio Connect: User Guide. Once you setup your personal key, you would use that in the httr::GET() command as your password argument.

Also, I would also suggest to use a regular /R script instead of one in the /test folder. That way you can eventually create a function that does both, deploy the new app, and then test it. Something similar to devtools::release(). That function does the checks and releases to CRAN, and it is expected to be run in an interactive R session. In your case, it could also ask for your password/Key using the rstudioapi::askForPassword() command.

this is great- thanks!

library(httr)

connectServer <- Sys.getenv("CONNECT_SERVER")
connectAPIKey <- Sys.getenv("CONNECT_API_KEY")

resp <- httr::GET(connectServer,
path = "/content/24/mean",
query = list(samples = 5),
add_headers(Authorization = paste0("Key ", connectAPIKey)))
result <- httr::content(resp, as = "parsed")

edit: deploying to TEST server and running tests on the TEST server would be nice. I'm not sure if I could do it with a function because the API is only updated every 15 minutes, so the function would have to wait until it has been updated.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.