rhttpopencpu

Is it possible to control the HTTP response behavior in openCPU?


According to the openCPU documentation, there are some default HTTP status codes and return types for a few situations. For example, when R raises an error, openCPU returns code 400 with a response type of text/plain.

While I believe it should be possible to control those things, is it possible to customize any of those things directly from R? For example, what if I wanted to return a JSON for a specific error in my R function, with a status code 503?


Solution

  • You can change their R package behavior by forking opencpu or via a local copy i.e. not sure if package allows this like a functionality but the responses are configured in res.R

    For e.g. this method in the link above uses 400 for error.

    error <- function(msg, status=400){
        setbody(msg);
        finish(status);
      }
    

    I will update the answer if I can confirm this is available without changing package code.

    UPDATE 17-04-2021

    You can write your serving html i.e. index.html which uses opencpu.js to call the corresponding R functions from your app, the return type can be requested to be json in the opencpu.js call. And in the R function , you can tryCatch() errors to send appropriate error code as a json argument.

    For e.g. in the stock example app you can see the file stock.js which calls the functions from R folder i.e.

    //this function gets a list of stocks to populate the tree panel
      function loadtree(){
        var req = ocpu.rpc("listbyindustry", {}, function(data){
          Ext.getCmp("tree-panel").getStore().setProxy({
            type : "memory",
            data : data,
            reader : {
              type: "json"
            }
          });
          Ext.getCmp("tree-panel").getStore().load();
        }).fail(function(){
          alert("Failed to load stocks: " + req.responseText);
        });
      }
    

    The corresponding R code being called is in listbyindustry.R, inside which you can tryCatch() and send custom json.