Encoding

Let’s consider an example. We develop an application which calculates factorial of a number:

Here is how request will be processed:

Let’s take a closer look to the response object and its body property:

str(response$body)
#>  chr "3628800"

As we can see it is a numeric value. HTTP response body however can’t be an arbitrary R object. It should be something that external systems can understand - either character vector or raw vector. Fortunately application helps to avoid writing boilerplate code to encode the body. Based on the content_type property it can find encode function which will be used to transform body into a http body.

Two immediate questions can arise:

  1. Why content_type is equal to text/plain?
    • This is because we can specify default content_type in Application constructor. It is text/plain by default, which means all the responses by default will have text/plain content type.
  2. How does application know how to encode text/plain? Can it encode any arbitrary content type?
    • Application by default is initialized with pre-defined [EncodeDecodeMiddleware] middleware. The logic on how to encode and decode request and response body is controlled by its ContentHandlers property. Out of the box it supports two content types - text/plain and application/json.

For instance app1 and app2 are equal:

Here is example on how you can get the actual function used for ‘application/json’ encoding:

We can manually override application default content-type:

And here is a little bit more complex example where we store a binary object in the body. We will use R’s native serialization, but one can use protobuf, messagepack, etc.

However function above won’t work correctly. Out of the box ContentHndlers doesn’t know anything about application/x-rds:

In order to resolve problem above we would need to either register application/x-rds content handler with ContentHandlers$set_encode() or manually specify encode function (identity in our case):

Now the answer is valid:

Decoding

RestRserve facilitates with parsing incoming request body as well. Consider a service which expects JSON POST requests:

The logic behind decoding is also controlled by [EncodeDecodeMiddleware] and its ContentHandlers property.