Suppose you’ve developed a very useful algorithm or statistical model and you need to itegrate it with some external system. Nowdays HTTP became de-facto a lingua-franca for this kind of tasks.

In this article we will demonstrate how to use RestRserve to build a basic REST API.

Workflow overview

Genrerally RestRserve workflow consists of several major steps:

  1. Create application with Application$new()
  2. Create a function which follows RestRserve API:
    • should take 2 arguments - request and response as an input. request and response are instances of RestRserve::Request and RestRserve::Response. It is important to remember that both request and response are mutable objects.
    • should modify response in place or raise() exception in case of error
  3. Register this function as a handler for an endpoint
  4. Start application

1. Create application

2. Define logic

For simplicity we will use Fibonacci number calculation as an algorithm we want to expose.

Create function which will handle requests.

3. Test endpoints

Now we can test our appliaction without starting it:

It is generally a good idea to write unit tests against application. One can use a common framework such as tinytest.

5. Start the app

Now all is ready and we can start application with Rserve backend. It will block R session and start listening for incoming requests.

6. Check it works

Check app can calculate fibonacci numbers:

Check out a swagger UI in the browser: http://localhost:8080/doc